C# - IHttpModule in ASP.NET

IHttpModule in C# is an interface used in ASP.NET for creating modules that observe and respond to HTTP requests. These modules can perform various tasks such as authentication, logging, or managing custom headers.

Methods:

  • Init(HttpApplication context): This method is called when the module initializes. It is where you can hook up event handlers to the various events exposed by the HttpApplication object.
  • Dispose(): This method provides a hook for any cleanup tasks, like releasing resources.

Modules implementing IHttpModule are registered in the web application's configuration, and they have access to the application's lifecycle events. This allows them to execute code at various stages of each request.

Example: Creating a Simple Logging Module

Let's create a simple IHttpModule implementation that logs the start and end of every request.

1. Define the Module:


using System;
using System.Web;

public class LoggingModule : IHttpModule
{
    public void Init(HttpApplication context)
    {
        context.BeginRequest += OnBeginRequest;
        context.EndRequest += OnEndRequest;
    }

    private void OnBeginRequest(object sender, EventArgs e)
    {
        HttpContext.Current.Response.Write("<p>Request started</p>");
    }

    private void OnEndRequest(object sender, EventArgs e)
    {
        HttpContext.Current.Response.Write("<p>Request ended</p>");
    }

    public void Dispose()
    {
        // Cleanup resources if needed
    }
}
    

2. Register the Module in Web.config:


<configuration>
  <system.webServer>
    <modules>
      <add name="LoggingModule" type="YourNamespace.LoggingModule" />
    </modules>
  </system.webServer>
</configuration>
    

Note: Replace YourNamespace with the actual namespace of your module.

Output Explanation:

When a request is made, the LoggingModule will output "Request started" at the beginning and "Request ended" at the end of the response. This will appear in the HTML of the browser's response.

This example gives a basic idea of how to create and use an IHttpModule in an ASP.NET application for tasks like logging. In real-world scenarios, modules can be more complex and handle a variety of tasks throughout the request lifecycle.

Points to Remember:
  1. IHttpModule is used for creating components in the request/response pipeline of an ASP.NET application.
  2. The Init method is where event subscriptions usually happen.
  3. Dispose is for resource cleanup, often with no implementation needed.
  4. The module must be registered in the application's configuration to be active.