Http://msdn.microsoft.com/en-us/magazine/cc301362.aspx One of ASP. net's most useful features is the extensibility of the HTTP pipeline, the path that data takes between client and server. this month I'm going to take a look at http modules in ASP. net. you can use them to extend your asp. net Applications by adding pre-and post-processing to each HTTP request coming into your application. for example, if you wanted custom authentication facilities for your application, the best technique wocould be to intercept the request when it comes in and process the request in a custom HTTP module. i'll start by looking at the HTTP pipeline. The HTTP PipelineTo understand the role of HTTP modules within ASP. net, you need to understand how the HTTP pipeline works. once an HTTP request comes in over port 80 (the regular http port or port 443 for HTTPS and the Secure Sockets Layer ), the request passes through a number of stages making up the HTTP pipeline before it's actually fielded by your application. Microsoft Internet Information Services (IIS) is the first participant in the chain. while ASP. net has its own object model, process isolation scheme, and session state management scheme based upon classes from. net Framework, IIS is still used to route the request to the ASP. net runtime. IIS maps the ASP. net file extensions to aspnet_isapi.dll, an ISAPI extension provided with ASP. net. the job of aspnet_isapi.dll is to forward the request to the ASP. net Worker Process, aspnet_wp.exe. from that point on, the request is wrapped up into an instance of httpcontext and piped through a number of ASP. net classes. the httpcontext class provided des members representing such things as the response and the request and also provided des security information along with anything else you might want to know about the request. The next step for the request is to pass through an instance of httpapplication. this stage is useful for maintaining application-scope methods, data, and events. i'll look at httpapplication closely since this class is pivotal in setting up HTTP modules. After the httpapplication object massages the request, it pushes the request through one or more httpmodule objects. there are a number of system-level HTTP modules, providing services ranging from authentication to state management to output caching. the number of modules that get to intercept the request is based upon settings within the host machine's machine. config file and the application's web. config file. in classic ASP, this role of providing pre-and post-processing fell upon ISAPI filters. it turns out that asp http modules are more straightforward to write. The final piece of the chain is the httphandler. if you 've been working with ASP. net for a while, you're familiar with the system. web. UI. page class. the page class is an httphandler object, implementing the interface ihttphandler. classes implementing ihttphandler can hook into the HTTP pipeline and service requests through the interface's processrequest method. Figure 1 HTTP Request
For each request that comes in, if the requested URI maps to an ASP. net extension, Asp. net will look for an ihttphandler implementation in the web. config file associated with that extension. if you change nothing in your web. config files and surf to An ASPX page, Asp. net creates a handler based on system. web. UI. page. alternatively, you can map individual HTTP handlers to distinct Uris through the Web. config file. figure 1 shows the path an HTTP request takes as it meanders through the HTTP pipeline. the events that are hooked to httpmodule classes include beginrequest, authenticaterequest, authorizerequest, and so on. ASP. net http modules An HTTP module is simply a class that implements the system. Web. ihttpmodule interface: public interface IHttpModule { void Dispose(); void Init(HttpApplication context); }
When an httpmodule is hooked into the pipeline (via an entry in web. config), the ASP. net runtime callthe module's init and dispose methods. init is called when the module attaches itself to the httpapplication object and dispose is called when the module is detached from httpapplication. the init and dispose methods represent the module's opportunity to hook into a variety of events exposed by httpapplication. these events include the beginning of a request, the end of a request, a request for authentication, and so forth. notice the httpapplication parameter passed in to the init method. usually, the init method takes the httpapplication object and maps event handlers to the desired events. Figure 2 shows some C # Code defining a simple httpmodule that attaches to an application's beginrequest and endrequest events to provide simple pre-and post-processing before and after each request. this code is compiled into an assembly that goes into the application's bin directory. to wire this handler up into the processing chain, the web. config File simply declares the module within the httpmodules section, as shown here: <configuration> <system.web>
The following code shows a plain vanilla ASPX page that uses the httpmodule in the chain:
ASP. net now routes all requests through the customhttpmodule's onbeginrequest method at the beginning of the request, and the onendrequest method at the end of the request. A simple ASPX page such as the one in Figure 3 will appear when you surf to the page.
Figure 3 A simple ASPX page
Beginrequest and endrequest aren't the only events you can intercept within an httpmodule. figure 4 shows all the available events you can route through an httpapplication and trap within an httpmodule. catching any of these events is simply a matter of setting up an event handler for the event you want to handle. figure 5 shows some C # code for an httpmodule intercepting the authenticaterequest event. Terminating requests early
One of the most common reasons for intercepting an HTTP request is to terminate the request early if something goes wrong. for example, if you're handling authentication by yourself, you might stop the request if the credentials are incorrect. if you're writing a SOAP server, you may be want to discontinue the request if a non-SOAP request comes through. the httpapplication class has a method named completerequest that finishes the request. you can call completerequest and set the statuscode and statusdescription properties of the context object to let the client know about the issue. figure 6 shows the interception of a request and its completion when the connection is not secure. System-provided modules
A good practice ASP. NET features are added using this httpmodule technique. these features include output caching, session state, Windows authentication, Forms authentication, passport authentication, URL Authorization, and file authorization. figure 7 shows these features and the modules responsible for them. Each of the predefined httpmodules is declared within the host-wide machine. config file, as shown in figure 8. The list of httpmodules attached to an app is represented as a collection of ihttpmodule references named httpmodulecollection, which can be accessed as the modules property of the httpapplication class. at run time, the collection nodes all the system-provided modules declared within machine. config as well as any specified in web. config. the httpmodulecollection is a list of references to ihttpmodule keyed by either the name of the module or an ordinal. you can interrogate the collection to find out which modules are attached, as shown in figure 9. figure 10 shows the modules as they're listed on the web page.
Figure 10 Attached httpmodules
The httpmodules are normally wired up by ASP. net as the application starts. if you want to manage the modules yourself, you may use the httpmodulecollection to obtain a reference to any of the modules and call ihttpmodule's init or dispose methods. alternatively you might manually load an httpmodule assembly and add the module to the list based upon certain crim criteria for your application. Httpmodules and Global. asax
ASP. net Applications may include a global file named Global. asax (known also as the ASP. NET application file ). global. asax lives in the root directory of your asp. NET application. when the application is loaded at run time, Asp. net parses the global. asax file and generates a runtime object derived from httpapplication. global. asax is optional, but when it's there, it includes des code for responding to application-level events raised by ASP. net and by HTTP modules. Global. asax is useful for handling events exposed by the modules that are handling the incoming request. for example, if you wanted to handle authentication within your global. asax file, you wocould do so by handling the application_onauthenticaterequest event, as shown here:
<Script language="C#" runat="server"> // Inside GLOBAL.ASAX void Application_OnAuthenticateRequest(Object Source, EventArgs Details) { // Put your authentication code here... } </script>
ConclusionMicrosoft has done a great job making sure ASP. net is extensible. one of the easiest ways to add pre-and post-processing to each request is by chaining an httpmodule into your application. in fact, Asp. net implements such features as Forms authentication and output caching through the httpmodule mechanic. they're easy to write-just create a class derived from ihttpmodule, write Event Handlers for the events you want to intercept, and create an entry into your web. config file to let ASP. net know about the httpmodule. in future columns I'll need e some of ASP. net's features, such as output caching and forms authentication, which have been implemented through HTTP modules. Send questions and comments for George to asp-net@microsoft.com.
|