Pages

Saturday, February 26, 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:

Http Request Lifecycle


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
        }
        void newBeginRequest(object sender, EventArgs e)
        {
            HttpApplication context = (HttpApplication)sender;
            string Url = context.Context.Request.RawUrl;
            if (!Url.Contains("SystemMonitoring.aspx"))
            {
                // show error page
            }
        }
    }
}

You can easily add/remove HttpModule via web.config file:


HttpHandlers and Usage:

HttpHandlers define actions for different type of requested files. They also can perform actions even if that file does not exist. An HTML page can perform all of the operations of an HttpHandler. But an HttpHandler has better performance and has more modularity than pages.

For creating an HttpHandler, you should implement IHttpHandler interface and then IsReusable and ProcessRequest methods. We can use HttpContext's Request and Response objects:

using System;
using System.Web;
namespace CodeBalance.Web
{
    public class ExampleHttpHandler : IHttpHandler
    {
        public void IsReusable(HttpApplication app)
        {
            // readonly.determines if this handler can be used in another requests
        }
        public void ProcessRequest(HttpContext context)
        {
            context.Response.Write("Hello World!");
        }
    }
}

You can easily add/remove HttpHandler via web.config file:

1 comment:

  1. A great post with out doubt. The information shared is of top quality which has to get appreciated at all levels. Well done keep up the good work.

    ReplyDelete