Accessing Session from an HttpModule
Thursday, July 28 2005 0 Comments
Today I wanted to extend my NHibernate implementation to allow formulti-page transactions for certain operations (that I control) andkeep with the cleaner ISession-per-HttpRequest pattern for everythingelse.
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 thosemethods. The problem is that SessionState is not loaded until after theBeginRequest 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 oneimplement the IRequiresSessionState or IReadOnlySessionStateinterfaces, but if you read the docs, those are marker interfaces forHttpHandlers only.

