HTTP
Modules
HTTP handlers are endpoints for communication. Instances of handler classes
consume HTTP requests and produce HTTP responses. HTTP modules are filters that
process HTTP request and response messages as they pass through the pipeline, examining
and possibly modifying their content. The pipeline uses HTTP modules to
implement its own infrastructure, most notably security and session management.
HTTP modules are simply classes that implement the
IHttpModule interface:
interface IHttpModule
{
// called to attach module to app events
void Init(HttpApplication app);
// called to clean up
void Dispose()
}
The Init method is called by an HttpApplication object when
the module is first created. It gives the module the opportunity to attach one
or more event handlers to the events exposed by the HttpApplication object.
The code in Figure 7 implements a simple HTTP module that handles
its HttpApplication object's BeginRequest and EndRequest events and measures
the elapsed time between them. In this example, the Init method uses normal
.NET techniques to attach the module's OnBeginRequest and OnEndRequest handlers
to the events fired by the HttpApplication object the module is being attached
to. The implementation of OnBeginRequest simply stores the time when the event
fired in the member variable starts. The implementation of OnEndRequest
measures the elapsed time since OnBeginRequest was called and adds that
information to the response message using a custom HTTP header.
The
OnEndRequest method takes advantage of the fact that the first parameter passed
to an event handler is a reference to the object that fired the event; in this
case, it is the HttpApplication object that the module is attached to. The
HttpApplication object exposes the Http-Context object for the current message
exchange as a property, which is exactly how OnEndRequest is able to manipulate
the HTTP response message.
Once an HTTP module class is implemented, it must be deployed. Deployment
involves two steps. As with an HTTP handler, you have to put the compiled
module code either in the bin sub directory of your Web server's virtual
directory or in the GAC so that the ASP.NET worker process can find it.
Then you have to tell the HTTP pipeline to create your module whenever a new
HttpApplication object is created to handle a request sent to your application.
You do this by adding an <httpModules> section to your virtual
directory's Web.config file, as shown here:
<configuration>
<system.web>
<httpModules>
<add
name="Elapsed"
type="Pipeline.ElapsedTimeModule, Pipeline"
/>
</httpModules>
</system.web>
</configuration>
In this example, the Web.config file tells the ASP.NET HTTP
pipeline to attach an instance of the Pipeline.ElapsedTimeModule class to every
HttpApplication object instantiated to service requests that target this
virtual directory.
No comments :
Post a Comment