Wednesday, 2 July 2014

HTTP Modules Explained With Example


Introduction
An HTTP module is an assembly that is called on every request made to your application. HTTP modules are called as part of the ASP.NET request pipeline and have access to life cycle events throughout the request. HTTP modules therefore give you the opportunity to examine incoming requests and take action based on the request. They also give you the opportunity to examine the outbound response and modify it.
ASP.NET HTTP modules are similar to ISAPI filters in that they run for all requests[which are unmanaged in nature]. However, HTTP Modules are written using  managed code and are fully integrated with the life cycle of an ASP.NET application. What are uses for HTTP modules
logging and Statistics  Because HTTP modules are called on every request, you can gather request statistics and logging information in a centralized module, rather than in each page of the application.Custom headers or footers. Because you can modify the outbound response, you can inject content such as custom header information into every page or XML Web service response.
ASP.NET uses modules to implement various application features, including forms authentication, caching, session state, and client script services.

How HTTP Modules Work

You register a custom HTTP modules in your 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 a module is created, its Init method is called and the module initializes itself.
In a module's Init method, you can subscribe to various application events such as BeginRequest or EndRequest by binding the events to methods you have created in the module. When these events are raised, the appropriate method in your module is called and the module can perform whatever logic is required, such as an authentication check or logging request information. During event handling, the module has access to the Context property of the current request. This enables you to redirect the request to an alternative page, modify the request, or perform any other request manipulation.

Now Creating an HTTP Module

You can create a custom HTTP module by creating a class that implements the IHttpModule interface and then registering it in the Web.config file. The general process for writing an HTTP module is:
 In my example, the module adds a Feedback form to Bottom of Every Aspx Page

To create a custom HTTP module class


  1. If your Web site does not already have an App_Code folder, create one under the root of the site.
  2. Create a class file named FeedbackModule.vb (for Visual Basic) or FeedbackModule.cs (for C#) in the App_Code directory.
  1. Add the following code to your class file:

    C# CODE

    using System;
    using System.Web;
    using System.Web.UI;
    public class FeedbackModule : IHttpModule
    {
        public FeedbackModule()
        {
        }
    
        public String ModuleName
        {
            get { return "FeedbackModule"; }
        }
    
        // 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));
        }
    
        private void Application_BeginRequest(Object source, 
             EventArgs e)
        {
        // Create HttpApplication and HttpContext objects to access
        // request and response properties.
            HttpApplication application = (HttpApplication)source;
            HttpContext context = application.Context;      
        }
        private void Application_EndRequest(Object source, EventArgs e)
        {
            HttpApplication application = (HttpApplication)source;
            HttpContext context = application.Context;
            context.Response.Write("FeedbackModule: End of Request");
        }
        public void Dispose()
        {
        }
    }
    
    

    VB.NET CODE

    Imports System.Web
    Imports System.Web.UI
    Public Class FeedbackModule
     Implements IHttpModule
     Public Sub New()
     End Sub
    
     Public ReadOnly Property ModuleName() As [String]
      Get
       Return "FeedbackModule"
      End Get
     End Property
    
     ' In the Init function, register for HttpApplication 
     ' events by adding your handlers.
     Public Sub Init(application As HttpApplication) Implements IHttpModule.Init
      AddHandler application.BeginRequest, (New EventHandler(AddressOf Me.Application_BeginRequest))
      AddHandler application.EndRequest, (New EventHandler(AddressOf Me.Application_EndRequest))
     End Sub
    
     Private Sub Application_BeginRequest(source As [Object], e As EventArgs)
      ' Create HttpApplication and HttpContext objects to access
      ' request and response properties.
      Dim application As HttpApplication = DirectCast(source, HttpApplication)
      Dim context As HttpContext = application.Context
     End Sub
     Private Sub Application_EndRequest(source As [Object], e As EventArgs)
      Dim application As HttpApplication = DirectCast(source, HttpApplication)
      Dim context As HttpContext = application.Context
      context.Response.Write("FeedbackModule: End of Request")
     End Sub
     Public Sub Dispose() Implements IHttpModule.Dispose
     End Sub
    End Class
    

    Registering the HTTP Module

    When you have finished creating the FeedbackModule class, you can register the module by creating an entry in the Web.config file.

    To register the module in the Web.config file

    1. If your Web site does not already have a Web.config file, create one under the root of the site.
    2. Add the following highlighted code to the Web.config file:
      <configuration>
          <system.web>
              <httpModules>
                 <add name="FeedbackModule" type="FeedbackModule"/>
              </httpModules>
          </system.web>
      </configuration>
      The code registers the module with the class name and the module name of FeedbackModule.

    Finally Testing/Use HTTP Module

    After you have created and registered your custom HTTP module you can test it.

    To test the custom HTTP module

    1. Create a Default.aspx page in your application.
    2. Request the Default.aspx page in a browser.The HTTP module appends a string to the beginning and end of the response. The module will automatically run on any request to a file whose extension is assigned to ASP.NET.


    Hope this helps..