WEBSITE

Programming Microsoft ASP.NET 3.5 : The HttpContext Class

7/25/2012 6:20:40 PM
During the various steps of the request’s chain of execution, an object gets passed along from class to class—this object is the HttpContext object. HttpContext encapsulates all the information available about an individual HTTP request that ASP.NET is going to handle. The HttpContext class is instantiated by the HttpRuntime object while the request processing mechanism is being set up. Next, the object is flowed throughout the various stages of the request’s lifetime, as Figure 1 demonstrates.
Figure 1. The HttpContext object, which encapsulates all the request information and is passed along through the HTTP pipeline until the client response is generated.


Properties of the HttpContext Class

Table 1 enumerates all the properties exposed by the HttpContext class. The class represent a single entry point for a number of intrinsic objects such as classic ASP’s intrinsics and ASP.NET-specific Cache and User objects.

Table 1. HttpContext Properties
PropertyDescription
AllErrorsGets an array of Exception objects, each of which represents an error that occurred while processing the request.
ApplicationGets an instance of the HttpApplicationState class, which contains the global and shared states of the application.
ApplicationInstanceGets or sets the HttpApplication object for the current request. The actual type is the global.asax code-behind class. Make a cast to access public properties and methods you might have defined in global.asax.
CacheGets the ASP.NET Cache object for the current request.
CurrentGets the HttpContext object for the current request.
CurrentHandlerGets the handler for the request that is currently being executed by the application. It is a read-only property that returns the value stored in Handler. Not supported in ASP.NET 1.x.
ErrorGets the first exception (if any) that has been raised while processing the current request.
HandlerGets or sets the HTTP handler for the current request.
IsCustomErrorEnabledIndicates whether custom error handling is enabled for the current request.
IsDebuggingEnabledIndicates whether the current request is in debug mode.
ItemsGets a name/value collection (hash table) that can be used to share custom data and objects between HTTP modules and HTTP handlers during the request lifetime.
PreviousHandlerGets the last handler before the current request was executed. Not supported in ASP.NET 1.x.
ProfileGets the object that represents the profile of the current user. Not supported in ASP.NET 1.x.
RequestGets an instance of the HttpRequest class, which represents the current HTTP request.
ResponseGets an instance of the HttpResponse class, which sends HTTP response data to the client.
ServerGets an instance of the HttpServerUtility class, which provides helper methods for processing Web requests.
SessionGets an instance of the HttpSessionState class, which manages session-specific data.
SkipAuthorizationGets or sets a Boolean value that specifies whether the URL-based authorization module will skip the authorization check for the current request. This is false by default. It is mostly used by authentication modules that need to redirect to a page that allows anonymous access.
TimestampGets a DateTime object that represents the initial timestamp of the current request.
TraceGets the TraceContext object for the current response.
UserGets or sets the IPrincipal object that represents the identity of the user making the request.

The Current property is a frequently used static member that returns the HttpContext object for the request being processed.

The Items property is a dictionary object—a hash table, to be exact—that can be used to share information between the modules and handlers involved with the particular request. By using this property, each custom HTTP module or handler can add its own information to the HttpContext object serving the request. The information stored in Items is ultimately made available to the page. The lifetime of this information is limited to the request.

Methods of the HttpContext Class

Table 2 lists the methods specific to the HttpContext class.

Table 2. HttpContext Methods
MethodDescription
AddErrorAdds an exception object to the AllErrors collection.
ClearErrorClears all errors for the current request.
GetAppConfigReturns requested configuration information for the current application. The information is collected from machine.config and the application’s main web.config files. Marked as obsolete in ASP.NET 2.0.
GetConfigReturns requested configuration information for the current request. The information is collected at the level of the requested URL, taking into account any child web.config files defined in subdirectories. Marked as obsolete in ASP.NET 2.0.
GetGlobalResourceObjectLoads a global resource. Not available in ASP.NET 1.x.
GetLocalResourceObjectLoads a local, page-specific resource. Not available in ASP.NET 1.x.
GetSectionReturns requested configuration information for the current request. Not available in ASP.NET 1.x.
RewritePathMostly for internal use; overwrites URL and query string of the current Request object.

Starting with ASP.NET 2.0, the GetSection method replaces GetConfig, which has been marked as obsolete and should not be used. If you have old code using GetConfig, just change the name of the method. The prototype is the same. Also, GetAppConfig is marked as obsolete in ASP.NET 2.0 and beyond. It has been replaced by GetWebApplicationSection, a static member of the new WebConfigurationManager class. Also, in this case, no changes are required to be made to the prototype. Let’s spend a few more words to dig out some interesting characteristics of other methods of the HttpContext class.

URL Rewriting

The RewritePath method lets you change the URL of the current request on the fly, thus performing a sort of internal redirect. As a result, the displayed page is the one you set through RewritePath; the page shown in the address bar remains the originally requested one. The change of the final URL takes place on the server and, more importantly, within the context of the same call. RewritePath should be used carefully and mainly from within the global.asax file. If you use RewritePath in the context of a postback event, you can experience some view-state troubles.

protected void Application_BeginRequest(object sender, EventArgs e)
{
   HttpContext context = HttpContext.Current;
   object o = context.Request["id"];
   if (o != null)
   {
      int id = (int) o;
      string url = GetPageUrlFromId(id);
      context.RewritePath(url);
   }
}
protected string GetPageUrlFromId(int id)
{
   // Return a full URL based on the input ID value.
   ...
}

The preceding code rewrites a URL such as page.aspx?id=1234 to a specific page whose real URL is read out of a database or a configuration file.

Loading Resources Programmatically

The $Resources and meta:resourcekey expressions for global and local resources, respectively, work only at design time. What if you need to generate text programmatically that embeds resource expressions, instead? Both the Page and HttpContext classes support a pair of programmatic methods to retrieve the content of resources embedded in the application.

GetGlobalResourceObject retrieves a global resource—that is, a resource defined in an .resx file located in the App_GlobalResources special folder. GetLocalResourceObject does the same for an .resx file located in the App_LocalResources special folder of a given page.

msg1.Text = (string) HttpContext.GetGlobalResourceObject(
     "Test", "MyString");
msg2.Text = (string) HttpContext.GetLocalResourceObject(
     "/Core35/Samples/Ch02/ResPage.aspx", "PageResource1.Title");

The first parameter you pass to GetGlobalResourceObject indicates the name of the .resx resource file without an extension; the second parameter is the name of the resource to retrieve. As for GetLocalResourceObject, the first argument indicates the virtual path of the page; the second is the name of the resource.

Other  
 
Top 10
Review : Sigma 24mm f/1.4 DG HSM Art
Review : Canon EF11-24mm f/4L USM
Review : Creative Sound Blaster Roar 2
Review : Philips Fidelio M2L
Review : Alienware 17 - Dell's Alienware laptops
Review Smartwatch : Wellograph
Review : Xiaomi Redmi 2
Extending LINQ to Objects : Writing a Single Element Operator (part 2) - Building the RandomElement Operator
Extending LINQ to Objects : Writing a Single Element Operator (part 1) - Building Our Own Last Operator
3 Tips for Maintaining Your Cell Phone Battery (part 2) - Discharge Smart, Use Smart
REVIEW
- First look: Apple Watch

- 3 Tips for Maintaining Your Cell Phone Battery (part 1)

- 3 Tips for Maintaining Your Cell Phone Battery (part 2)
VIDEO TUTORIAL
- How to create your first Swimlane Diagram or Cross-Functional Flowchart Diagram by using Microsoft Visio 2010 (Part 1)

- How to create your first Swimlane Diagram or Cross-Functional Flowchart Diagram by using Microsoft Visio 2010 (Part 2)

- How to create your first Swimlane Diagram or Cross-Functional Flowchart Diagram by using Microsoft Visio 2010 (Part 3)
Popular Tags
Video Tutorail Microsoft Access Microsoft Excel Microsoft OneNote Microsoft PowerPoint Microsoft Project Microsoft Visio Microsoft Word Active Directory Exchange Server Sharepoint Sql Server Windows Server 2008 Windows Server 2012 Windows 7 Windows 8 Adobe Flash Professional Dreamweaver Adobe Illustrator Adobe Photoshop CorelDRAW X5 CorelDraw 10 windows Phone 7 windows Phone 8 Iphone