Enabling Session State in SharePoint 2010

Background

Don’t know when this will be needed, but whenever required it important to know that how do we enable Session State in SharePoint 2010. Basically after enabling this we would be able to use session variables in our SharePoint 2010 application and Web Services.

Let’s Get Cracking

In order to enable this first thing that we have to do is edit our web.config file. Add the following entry in httpModules section

<httpModules>
    <add name="Session" type="System.Web.SessionState.SessionStateModule" />
</httpModules>

This is not it, next steps are more important. Go to your web application and this Session State module to IIS 7.x managed pipeline.

  1. Go to Run and type inetmgr

    Run-IIS

    Run-IIS

  2. Select your Web Application in left tree and double click Modules under IIS section in Feature View pane.

    Select-WebApplication-Modules

    Select-WebApplication-Modules

  3. Click on “Add Managed Module…” from Actions pane

    Add-Managed-Module

    Add-Managed-Module

  4. In Add Managed Module dialog enter “Session State” or any other name of your choice and select following item from “Type” drop down.
    Select-Managed-Module-Name-And-Type

    Select-Managed-Module-Name-And-Type

    System.Web.SessionState.SessionStateModule, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
  5. Finally to be on safer side restart the IIS.

    Restart-IIS

    Restart-IIS

After all this session state will be enabled in your web application or web service.

Example

Add page in your SharePoint project and add “EnableSessionState” attribute in page directive and set its value to “True

In code behind add this code to add a session variable and value for the same and display the value of session variable in label.

if (Session.Count <= 0)
{
	Session.RemoveAll();
	Session.Add("LongOp", "on");
}

lbl.Text = Session[0].ToString();

Happy SharePointing 🙂

Tagged with: , ,