Accessing Request and Session data in ASP.net HTTP Handler

As part of a proof of concept I’m working on, I had to create a simple HTTP Handler which had to access the current HTTP Request and session data as it was coming into the website, I used a HTTP Handler because the Global.asax does not allow access to the request data.

The first thing to do is to create a new class library as the handler cannot be created in the same project as the website itself,  instead it needs to be accessed via an external assembly.

The class then needs to implement IHttpModule and IRequireSessionState, if it requires access to the session data.

The class would look something like this:

public class LoggedInCheckerModule : IHttpModule, IRequiresSessionState

Then two methods need to be implemented, public void Dispose() and public void Init(HttpApplication context).

Within the Init method, you add the code for which you want the handler to access.  context contains all the information about the request.

PITFALL: context.Request etc fails.  Instead, you need to do context.Context.Request 🙂

After you have coded your handler, in your website web.config you add the reference to the module you created.  Name is a local friendly name,  type is then the module class, and the name of the assembly its located in.


type=”LoggedInCheckerModule,
Modules” />

 

That’s it!  The request will then go via the HTTP Handler before hitting your website.

 

UPDATE: Well, that’s not it. There is a small problem with this code/concept – doesn’t work perfectly. I was doing the processing in the Init method (Silly me, this is when the module is launched – my fault bad testing/lack of requirement for it). However, the code below does work – trust me 🙂

In the Init method, I want to setup an event handler to the PreRequestHandlerExecute which occurs “just before ASP.NET begins executing a handler such as a page or XML Web service.” (MSDN)

public void Init(HttpApplication app)
{
    app.PreRequestHandlerExecute += new EventHandler(app_PreRequestHandlerExecute);
}

This will get called every time a new request comes into the site, as you know HTTP is stateless so this also is called when a current user requests a different page or a postback is made. 

Within the app_PreRequestHandlerExecute you can do the processing to access the Session and Request data.  Everything you need is stored within the HttpContext.Current static method.  For example HttpContext.Current.Session[“username”]; and HttpContext.Current.Request.CurrentExecutionFilePath;

I’ve uploaded the code for my module, Do not use this in production code, its just the concept I had to do for my project.  Feel free to use the layout, just rip out my method logic.

Code:

http://blog.benhall.me.uk/code/aspnet/LoggedInCheckerModule.cs.txt

 

3 thoughts on “Accessing Request and Session data in ASP.net HTTP Handler”

Leave a Reply

Your email address will not be published. Required fields are marked *