Using session state in HttpModule – SharePoint 2010

I recently created a HTTPModule for a SharePoint 2010 web application and I planned to store some values in session variables.

In my httpmodule, I am using the context_PreRequestHandlerExecute as an entry point :

void context_PreRequestHandlerExecute(object sender, EventArgs e)
{
          HttpContext ctx = ((HttpApplication)sender).Context        

          ctx.Session.Add(“Phil Lau”, “SharePoint”);
           …
}

I was expected to be able to use the Session state from the get-go, but no, it returned an null exception when attempting to use the Session state to store a value. In the Visual Studio Immediate window, ctx.Session returns null. This prevented me from storing values into the session state.

The solution 🙂 (Yes, you have to enable session state in SharePoint 2010 web applications)

 

Two things I had to do:

1) Enable Session State for the web application

a)  Open up the web.config for your web application, do a CTRL+F for sessionstate

b) When you find <pages enableSessionState=”false” enableViewState=”true” … change enableSessionState to
“true”

c)  Save web.config

2) Add the Session http module into my web.config

a) In same web.config as above, go to the httpmodules section. This section looks like this <modules runAllManagedModulesForAllRequests=”true”> <remove name=”AnonymousIdentification”/> …….

b) Locate <remove name=”Session” /> and delete it

c) Save web.config and refresh your web site

 In the Visual Studio Immediate window, ctx.Session returns null. This prevented me from storing values into the session state.

 

Done! This worked for me, I was able to access and use the session state!