How to use HttpModules in ASP.NET

By FoxLearn 1/7/2025 9:18:21 AM   43
HTTP modules in ASP.NET are components that intercept incoming requests and inject pre-processing logic into the request processing pipeline.

They are called on every request and have access to the request's life cycle events, allowing them to modify both the request and the response.

Custom HTTP Module

At first glance, the custom HttpModule might look like this:

public class CustomHttpModule : IHttpModule
{
    public void Dispose()
    {
        throw new NotImplementedException();
    }

    public void Init(HttpApplication context)
    {
        throw new NotImplementedException();
    }
}

Subscribing to Events

To subscribe to events in your custom HTTP module, you can use the following code:

public void Init(HttpApplication context)
{
    context.BeginRequest += new EventHandler(OnBeginRequest);
    context.EndRequest += new EventHandler(OnEndRequest);            
    context.LogRequest += new EventHandler(OnLogRequest);
}

Logging Requests

The OnLogRequest method logs the path of each incoming request to a text file.

public void OnLogRequest(object sender, EventArgs e)
{
    HttpContext context = ((HttpApplication)sender).Context;
    string filePath = @"D:\Logs\requestLog.txt";
    using (StreamWriter streamWriter = new StreamWriter(filePath, true))
    {
        streamWriter.WriteLine(context.Request.Path);
    }
}

Here’s the complete implementation of the custom HTTP module:

public class CustomHttpModule : IHttpModule
{
    public void Init(HttpApplication context)
    {
        context.BeginRequest += new EventHandler(OnBeginRequest);
        context.EndRequest += new EventHandler(OnEndRequest);          
        context.LogRequest += new EventHandler(OnLogRequest);
    }

    public void OnLogRequest(object sender, EventArgs e)
    {
        HttpContext context = ((HttpApplication)sender).Context;
        string filePath = @"D:\Logs\requestLog.txt";
        using (StreamWriter streamWriter = new StreamWriter(filePath, true))
        {
            streamWriter.WriteLine(context.Request.Path);
        }
    }

    public void OnBeginRequest(object sender, EventArgs e)
    {
        // Custom code for beginning of request
    }

    public void OnEndRequest(object sender, EventArgs e)
    {
        // Custom code for end of request
    }

    public void Dispose()
    {
        // Dispose resources if necessary
    }
}

Registering the Custom HTTP Module

To use this custom HTTP module, you need to create an ASP.NET application, build the solution, and reference the custom HTTP module. Then, register it in the web.config file:

<system.webServer>
    <modules>
        <add name="CustomHttpModule" type="YourNamespace.CustomHttpModule, YourAssembly" />
    </modules>
</system.webServer>

Asynchronous HTTP Module

For improved performance, especially for long-running I/O-bound tasks, you can implement asynchronous operations in your HTTP module. Here’s how you can modify the module for asynchronous handling using the EventHandlerTaskAsyncHelper class from .NET Framework 4.5:

public void Init(HttpApplication context)
{
    EventHandlerTaskAsyncHelper asyncHelperObject = new EventHandlerTaskAsyncHelper(LogRequest);
    context.AddOnPostAuthorizeRequestAsync(asyncHelperObject.BeginEventHandler, asyncHelperObject.EndEventHandler);
}

private async Task LogRequest(object sender, EventArgs e)
{
    HttpContext context = ((HttpApplication)sender).Context;
    string filePath = @"D:\Logs\requestLog.txt";
    using (StreamWriter streamWriter = new StreamWriter(filePath, true))
    {
        await streamWriter.WriteLineAsync(context.Request.Path);
    }
}

Here’s the final implementation of the asynchronous custom HTTP module:

public class CustomHttpModule : IHttpModule
{
    public void Init(HttpApplication context)
    {
        EventHandlerTaskAsyncHelper asyncHelperObject = new EventHandlerTaskAsyncHelper(LogRequest);
        context.AddOnPostAuthorizeRequestAsync(asyncHelperObject.BeginEventHandler, asyncHelperObject.EndEventHandler);
    }

    private async Task LogRequest(object sender, EventArgs e)
    {
        HttpContext context = ((HttpApplication)sender).Context;
        string filePath = @"D:\Logs\requestLog.txt";
        using (StreamWriter streamWriter = new StreamWriter(filePath, true))
        {
            await streamWriter.WriteLineAsync(context.Request.Path);
        }
    }
}

Benefits of Asynchronous HTTP Module

Using an asynchronous HTTP module ensures that long-running I/O operations, like logging requests, don’t block the processing of incoming requests, improving the performance and responsiveness of the application.