Programming Microsoft ASP.NET 2.0 Core Reference

 

The HttpContext Class

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 12-3 demonstrates.

Figure 12-3: The HttpContext object encapsulates all the request information and gets flowed through the HTTP pipeline until the client response is generated.

Properties of the HttpContext Class

Table 12-6 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 12-6: HttpContext Properties

Property

Description

AllErrors

Gets an array of Exception objects, each of which represents an error that occurred while processing the request.

Application

Gets an instance of the HttpApplicationState class, which contains the global and shared states of the application.

ApplicationInstance

Gets 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.

Cache

Gets the ASP.NET Cache object for the current request.

Current

Gets the HttpContext object for the current request.

CurrentHandler

Gets the handler for the request that is currently being executed by the application. Not supported in ASP.NET 1.x.

Error

Gets the first exception (if any) that has been raised while processing the current request.

Handler

Gets or sets the HTTP handler for the current request.

IsCustomErrorEnabled

Indicates whether custom error handling is enabled for the current request.

IsDebuggingEnabled

Indicates whether the current request is in debug mode.

Items

Gets 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.

PreviousHandler

Gets the last handler before the current request was executed. Not supported in ASP.NET 1.x.

Profile

Gets the object that represents the profile of the current user. Not supported in ASP.NET 1.x.

Request

Gets an instance of the HttpRequest class, which represents the current HTTP request.

Response

Gets an instance of the HttpResponse class, which sends HTTP response data to the client.

Server

Get an instance of the HttpServerUtility class, which provides helper methods for processing Web requests.

Session

Gets an instance of the HttpSessionState class, which manages session-specific data.

SkipAuthorization

Gets 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.

Timestamp

Gets a DateTime object that represents the initial timestamp of the current request.

Trace

Gets the TraceContext object for the current response.

User

Gets 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 12-7 lists the methods specific to the HttpContext class.

Table 12-7: HttpContext Methods

Method

Description

AddError

Adds an exception object to the AllErrors collection.

ClearError

Clears all errors for the current request.

GetAppConfig

Returns 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.

GetConfig

Returns 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.

GetGlobalResourceObject

Loads a global resource. Not available in ASP.NET 1.x.

GetLocalResourceObject

Loads a local, page-specific resource. Not available in ASP.NET 1.x.

GetSection

Returns requested configuration information for the current request. Not available in ASP.NET 1.x.

RewritePath

Mostly for internal use; overwrites URL and query string of the current Request object.

In ASP.NET 2.0, the GetSection 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. GetAppConfig is also marked as obsolete in ASP.NET 2.0. It has been replaced by GetWebApplicationSection, a static member of the new WebConfigurationManager class. Also in this case, no changes to the prototype are required. Let's take some time 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 important, 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); } }

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

In Chapter 2, we discussed expressions allowed in ASP.NET 2.0 pages to bind control properties to embedded global or local resources. The $Resources and meta:resourcekey expressions for global and local resources, respectively, work only at design time. What if you instead need to generate text programmatically that embeds resource expressions? 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( "/ProAspNet20/Samples/Ch02/ResPage.aspx", "PageResource1.Title");

The first parameter you pass to GetGlobalResourceObject indicates the name of the .resx resource file without 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.

 

Категории