C# – Access Session Variable from HTTPModule

asp.netchttpmodule

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"

Best Answer

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);
}