Showing posts with label REquest pipeline. Show all posts
Showing posts with label REquest pipeline. Show all posts

Thursday, January 15, 2009

HTTP Modules in detail

HTTP modules, part of ASP.Net request pipeline, are called on every request made to an application and can access life cycle events through out the request. They are like ISAPI filters as they are invoked for all requests. Once the request passes through all of the HTTP modules, it is eventually served by an HTTP handler. The HTTP handler performs some processing on it, and the result again passes through the HTTP modules in the pipeline.

Features like form authentication, caching, sessionstate, client script services are implemented using modules. As part of a request, the module is called to perform tasks that a single page request cannot perform. They use application events, raise events that can be handled in the Global.asax file.

To receive notifications from the request pipeline, you need to register HTTP modules in the application's web.config file. When ASP.NET creates an instance of the HttpApplication class that represents your application, instances of any modules that have been registered are created.

When you create a module, its Init method is called, and then the module initializes itself.
In the module's Init method, you can subscribe to various application events such as BeginRequest or EndRequest by binding the events to methods in the module. When application events are raised, you need to call the appropriate method in your module to perform the required logic, such as checking authentication or logging request information. During event handling, the module can access the Context property of the current request to redirect the request to an alternative page, modify the request, or perform any other request manipulation. Otherwise, when the module's event handler has finished running, ASP.NET calls the next process in the pipeline.


public class MyFirstModule : IHttpModule
{
public MyFirstModule ()
{
}

public String ModuleName
{
get { return "MyModule"; }
}
}

To register in web.config

.configuration.
.system.web.
.httpModules.
.add name="MyFirstModule" type="MyFirstModule"/.
.httpModules.
./system.web.
./configuration.

Note: Replace the "." with opening and closing tags.



To write a handler for the Init method.
// In the Init function, register for HttpApplication events by adding
your handlers.
public void Init(HttpApplication application)
{
application.BeginRequest += (new EventHandler(this.Application_BeginRequest));
application.EndRequest += (new EventHandler(this.Application_EndRequest));
}

Note : During the processing of an http request, only one HTTP handler will be called, whereas more than one HTTP modules can be called
Source of Reference: MSDN
 
Google