Cambia Research - Supporting the Microsoft .NET Developer Community Supporting the Microsoft .NET Developer Community  

     | Home  | Articles  | Categories  | Coders  | Search  | Submit  | Contact Us    
Microsoft's only factory asset is the human imagination. --Bill Gates

Share Your Knowledge! -- Create and submit your articles the easy way with WebWriter.

Updated:12:55 AM CT Jan 10, 2007
Posted:11:09 PM CT Jan 09, 2007

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?

Author: Steve Lautenschlager

SnippetC#.NETASP.NETServer SideWeb

 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 HttpServerUtility GetCurrentCacheObject()
{
   return HttpContext.Current.Cache;
}

Add New Comment
Using the HttpContext object
Sreedhar Vankayala05 Sep 07, 16:56Reply 
re: Using the HttpContext object
Steve Lautenschlager05 Sep 07, 19:47Reply 
CR Comments by Cambia Research
advertisement
 
Steve Lautenschlager (steve)
Steve is the founder and creator of Cambia Research. Developing and maintaining the site combines his passions for technology, writing and education.
Steve holds a Ph.D. in particle physics from Duke University, has worked at CERN, the European center for particle physics (where the web was born) and in Microsoft's web division with microsoft.com, msnbc.com and other web properties. Steve is a web consultant specializing in Microsoft.NET technologies. Read more here.


 
Copyright © Cambia Research 2002-2007. All Rights Reserved. steve [ at ] cambiaresearch.com