What is a HttpModule ?

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. However, they are written in managed code and are fully integrated with the life cycle of an ASP.NET application.

Typical uses for HTTP modules include:

  • Security
  • Statistics and logging
  • Custom headers or footers

In simpler words, An HTTP Module lets you add code that will be run every time a page is requested, so it’s a great solution for adding custom security checks.

Creating an HTTP Module

public class IsLocalHostHttpModule:IHttpModule
{
    public void Init(HttpApplication context)
    {
        context.BeginRequest += new EventHandler(HandleBeginRequest);
    }

    public void HandleBeginRequest(object source, EventArgs e)
    {
        HttpContext context = ((HttpApplication)source).Context;
        string ipAddress = context.Request.UserHostAddress;
        if (ipAddress != "::1" || ipAddress != "127.0.0.1")
        {
            context.Response.StatusCode = 403;
        }
    }

    public void Dispose() {}
}

Registering an HTTP Module

<configuration>
    <system.web>
        <httpModules>
            <add 
                 name="IsLocalHostHttpModule" 
                 type="Project.Folder.IsLocalHostHttpModule"
            />
            <!-- full qualified name should be mentioned in type -->
        </httpModules>
    </system.web>
</configuration>

References