Tuesday 22 February 2011

Asp.Net: Simple HttpModule sample using Session

Question:
How do I create a HttpModule in asp.net ?
How do I get access to the Session in a HttpModule ?
Do you have a simple sample of a HttpModule in dot.net ?



Answer:
A HttpModule intercepts all requests to the asp.net application (not only pages).
That allows you for example to filter requests and check permissions.

You can subscribe to a variety of events of the application object.

If you want to access the Session property of the application in your event handler method you must subscribe to AcquireRequestState or later !

To create a HttpModule follow these steps:
  1. Create a class that implements IHttpModule
  2. Subscribe to some events.
  3. Register module in the web.config

A very simple HttpModule
public class SimpleModule : IHttpModule
{
    void IHttpModule.Init(HttpApplication application)
    {
        application.BeginRequest += new System.EventHandler(BeginRequest);
        application.AcquireRequestState += new EventHandler(application_AcquireRequestState);
    }
    public void BeginRequest(object sender, EventArgs e)
    {
        // no session here but you could filter urls etc.
    }
    void application_AcquireRequestState(object sender, EventArgs e)
    {
        // We need the session, thus BeginRequest is too early
        HttpApplication app = sender as HttpApplication;
        app.Session.Add("Message", "hello module");

        // you could test whether this is a page request like this
        bool isPageRequest = app.Context.Request.RawUrl.Contains(".aspx");
    }
    public void Dispose()
    {
    }
}

Register your HttpModule (for IIS 7)

  
    
      
      
  

1 comment:

Ali Raza said...

I copied the code and add specified XML in the web.config.... but AcquireRequestState event is firing. is there anu thing else u did to run this code.

I am using dotnet framework 3.5 and windows 7.