Thursday, July 28, 2005

Accessing Session from an HttpModule

Today I wanted to extend my NHibernate implementation to allow for multi-page transactions for certain operations (that I control) and keep with the cleaner ISession-per-HttpRequest pattern for everything else.

To do that I had to modify my HttpModule to allow for this check, but I had no access to the SessionState here.  Why is that?

Here’s what I was doing in my HttpModule:

public void Init(HttpApplication application)

{
//add event handlers
 application.BeginRequest += new EventHandler(context_BeginRequest);
 application.EndRequest += new EventHandler(context_EndRequest);
}

I was creating and disconnecting my ISession object inside of those methods. The problem is that SessionState is not loaded until after the BeginRequest had fired and before the EndRequest had fired. (specifically it is accessibly after the AcquireRequestState event). So, changing my code to this worked:

public void Init(HttpApplication application) 
{
application.PreRequestHandlerExecute += new EventHandler(application_PreRequestHandlerExecute);
application.PostRequestHandlerExecute += new EventHandler(application_PostRequestHandlerExecute);
}

Also, I saw some people online incorrectly suggesting that one implement the IRequiresSessionState or IReadOnlySessionState interfaces, but if you read the docs, those are marker interfaces for HttpHandlers only.

Comments are closed.