Programming is like sex, one mistake and you have to support it for the rest of your life. --Michael Sinz

Using the HttpContext object

How can I get access to the Context object when I'm not in the code-behind of an ASPX page?

Summary

The HttpContext object in the System.Web namespace encapsulates all of the information related to one request and allows you to access that information within or outside of the actual aspx page that is being processed.

A lot of the asp.net code I write goes in class libraries rather than the aspx page so that I can re-use it for multiple pages and sites. However, some readers may have discovered that the Request and Response objects are not available outside of the aspx page.

Actually these objects are available and HttpContext is the way to get at them.

Methods to retrieve the current http related objects: Request, Response, Server, Session, Cache
using System.Web

// Get the current Session object
public static HttpSessionState GetCurrentSessionObject()
{
   return HttpContext.Current.Session;
}

// get the current Response object
public static HttpResponse GetCurrentResponseObject()
{
   return HttpContext.Current.Response;
}

// get the current Request object
public static HttpRequest GetCurrentRequestObject()
{
   return HttpContext.Current.Request;
}

// get the current Server object
public static HttpServerUtility GetCurrentServerObject()
{
   return HttpContext.Current.Server;
}

// get the current Cache object
public static Caching.Cache GetCurrentCacheObject()
{
   return HttpContext.Current.Cache;
}
 

Version: 6.0.20200920.1535