ASP.net Tip: Session State Service

July 8, 2010 by ASP.NET   IIS  

Traditionally ASP sessions are dependent/bound to the process/machine that hosts it, which proves to be quite an annoying limitation - since whenever the process fails/recycles, or becomes unavailable (e.g. web server farm), session state is lost.

In ASP.net however, Microsoft added the ASP.net Session State Service in which they made it possible to move sessions outside the current process/machine - which means restarting/recycling a pool wont affect our sessions.

By default ASP.net sessions are still dependent/bound to the process/machine that hosts it, we need to enable/configure sessions to run out of process.

Lets have a look at how to do that.

First of all make sure that the ASP.Net State Service is started. (Generally its a good idea to set its startup type to automatic)



Secondly within your web.config add/edit the sessionState node (located within the system.web node), like this:

<sessionState mode="StateServer"
      stateConnectionString="tcpip=localhost:42424"
      cookieless="false"
      timeout="20"/>

This enables the web application to connect to the state service (located on the localhost in this example)

Note: In IIS 7.0 and higher, Microsoft added an UI to manage session state configurations.



You might have noticed (from the screenshot at the top) that ASP.net supports different modes of session state e.g. In process (default), Custom, State Server (already discussed) and SQL Server.

The sessionState node used to configure SQL Server mode (storing sessions in the db), looks something like this:

<sessionState mode="SQLServer" sqlConnectionString="Server=.\sqlexpress;User ID=username;Password=password" />

In order to use SQL Server mode you need to run the following command, which creates a database etc within the specified SQL Server instance:

aspnet_regsql.exe -S .\sqlexpress -E -ssadd -sstype p

In some future post I will demonstrate how to create a custom session state store/handler.

ASP.net 4.0:

In ASP.net 4.0 Microsoft added an option to compress session state
<sessionState mode="StateServer"
      stateConnectionString="tcpip=localhost:42424"
      cookieless="false"
      timeout="20" compressionEnabled="true" />

Some sources:
http://msdn.microsoft.com/en-us/library/ms178586.aspx
http://msdn.microsoft.com/en-us/library/ms229862.aspx
http://technet.microsoft.com/en-us/library/cc732412(WS.10).aspx
http://msdn.microsoft.com/en-us/library/x28wfk74.aspx" target="_blank


Leave a Comment