Monday, February 28, 2011

A Brief Explanation of HttpModule and HttpHandler

An HTTP request from client to server can be explained as a chain of IIS, AspNET_ISAPI, Asp.NET Work Processor, HttpModules and HttpHandlers. The last part of the chain which is HttpHandler, creates the HTML and sends the result to HttpModule. AspNet_IASPI.dll is used for Asp.NET pages. And chain completes in reverse order this time, as shown below:

httphandlersandmodules.PNG


HttpModules and Usage:
We can use several predefined methods of the Global.asax file to perform actions on start/end of the application, on start/end of the request etc., and an HttpModule  do the same thing with more modularity. So, an HttpModule can be thought as a modular alternative of Global.asax file and its usage is recommended.

For creating an HttpModule, you should implement IHttpModule interface, and then Init and Dispose methods. We can use HttpApplication object:

using System;
using System.Web;
namespace CodeBalance.Web
{
   public class ExampleHttpModule : IHttpModule
   {
       public void Init(HttpApplication app)
       {
           app.BeginRequest += new EventHandler(newBeginRequest);
       }
       public void Dispose()
       {
           // dispose operations, if necessary
       }

Read more: CodeBalance