There are two ways to write error-free programs; only the third works. --Alan J. Perlis
Welcome to my blog and project site for Microsoft.NET development.

I've been a full time .NET developer for ten years, but I didn't start my professional life as a programmer ... more
Share/Print this page:

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?

By steve on January 09, 2007.
Updated on January 22, 2012.
Viewed 49,551 times (1 times today).
Article TypesLanguagesSoftware DevelopmentTechnologiesTechnologiesTopics
SnippetC#Server side.NETASP.NETWeb

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;
}
Back to Top

User Comments (4)

Posted 2007 Sep 05 16:56 PM. reply
// get the current Cache object
public static Caching.Cache GetCurrentCacheObject()
{
return HttpContext.Current.Cache;
}

Sreedhar Vankayala
Reply 2007 Sep 05 19:47 PM by steve. reply
Thanks for catching that error. Yes, the return value on GetCurrentCacheObject() should be a Cache object (from the System.Web.Caching namespace).
Reply 2011 Nov 01 18:55 PM by steve. reply
This is fixed in the article now.
Posted 2012 Jan 31 02:30 AM. reply
Static websites contains web pages with fixed content. It can be built by simply creating a few HTML pages and publishing them to a Web server. <a href="http://www.universalutsi.com/">Static websites</a>

Static Websites
Post Your Comment
  You may post without logging in or login here.
Display Name: Required.
Email: Required. Will not be shown. Used for identicon.
Comment:
Allowed tags: <quote></quote>, <code></code>, <b></b>, <i></i>, <u></u>, <red></red>
 
   Please type text as shown in the image at left.