Please navigate to the bottom of the page for Table of Contents

Thursday, June 2, 2011

ASP.NET HttpModule explained

An HTTP module is a simple class that can plug themselves into the request-processing pipeline. They do this by hooking into a handful of events thrown by the application as it processes the HTTP request. HTTP modules let you examine incoming and outgoing requests and take action based on the request.

To create an HttpModule, you simply create a class that derives from the System.Web.IHttpModule interface. This interface requires you to implement two methods: Init and Dispose. The simple code snippet below shows an HttpModule that appends a simple message at the end of every page output in your application.

using System;
using System.Web;

namespace WebApplication2
{
public class PageTimerModule : IHttpModule
{
private HttpApplication _application = null;

public void Dispose()
{
}

public void Init(System.Web.HttpApplication context)
{
// save the context
_application = context;
// handle the end request
context.EndRequest += new EventHandler(context_EndRequest);
}


// tag a message at the end of the page
void context_EndRequest(object sender, EventArgs e)
{
string message = string.Format("Generated at {0}",
System.DateTime.Now.ToString());
// stream it at the end of the response
_application.Context.Response.Write(message);
}
}
}


To use this module, we need to modify the web.config and add a reference to this module. This will let ASP.NET know that you want to include the module in the request processing pipeline.


<?xml version="1.0"?>

<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />

<httpModules>
<add name="PageTimerModule"
type="WebApplication2.PageTimerModule, WebApplication2"/>
</httpModules>
</system.web>

<!-- For IIS 7, we also need to define it in the web server section-->
<system.webServer>
<modules>
<add name="PageTimerModule"
type="WebApplication2.PageTimerModule, WebApplication2"/>
</modules>
</system.webServer>
</configuration>


That’s it. HttpModules provide you with a simple and effective way to tap into the ASP.NET request pipeline. In the next post we will look into HttpHandlers.

1 comment:

  1. Nice explaination Nikhil. Hope to see more advanced interview questions on ASP.NET.

    Regards,
    Parag

    ReplyDelete