Access Session Variable from HTTPModule

ysr picture ysr · Apr 18, 2012 · Viewed 7.3k times · Source

How can I access session variable from the HttpModule?

I set following session variable in .cs page, which I want access in the HttpModule:

Session["username"] = "BLAH"

Answer

Fabio Testa picture Fabio Testa · Feb 18, 2016

I suggest a less invasive approach. Just force ASP.NET runtime to expose session to your module with SetSessionStateBehavior() (implementations of IRequiresSessionState are considered only for IHttpHandlers).

public void Init(HttpApplication httpApp)
{
   //SESSION WILL BE AVAILABLE IN ALL EVENTS FROM PreRequestHandlerExecute TO PostRequestHandlerExecute
   httpApp.PostRequestHandlerExecute += OnPostRequestHandlerExecute;
   //THIS IS THE IMPORTANT LINE
   httpApp.Context.SetSessionStateBehavior(SessionStateBehavior.ReadOnly);
}