Click here to Skip to main content
15,880,469 members
Articles / Web Development / ASP.NET
Article

ASP.NET Session Management Internals

Rate me:
Please Sign up or sign in to vote.
3.52/5 (28 votes)
2 Aug 20044 min read 310.8K   85   18
This article goes through the internals of ASP.NET session management.

Sample Image - HttpSessionState.jpg

Introduction

Every ASP.NET application needs to manage client session information because of stateless nature of HTTP protocol. A question that is often asked in newsgroups, forums, and mailing lists is that, how does ASP.NET Session Management work, and which technique in ASP.NET is the best way to manage session in a web farm or high volume web site with large number of concurrent users? We will begin with a quick overview of ASP.NET session management alternatives, then dive into ASP.NET Session Management internals, and make some recommendations at the end.

ASP.NET Session Management Alternatives:

ASP.NET provides three modes of session state storage controlled by mode attribute of <sessionState> tag in your web application’s Web.config file. Below is a sample of this tag:

XML
<sessionState 
    mode="InProc"
    stateConnectionString="tcpip=127.0.0.1:42424"
    sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes"
    cookieless="false" 
    timeout="20" />
AttributeOptionDescription
mode Specifies where to store the session state.
 OffDisables session state management.
 InProcSession state is stored locally in memory of ASP.NET worker process.
 StateServerSession state is stored outside ASP.NET worker process and is managed by Windows service. Location of this service is specified by stateConnectionString attribute.
 SQLServerSession state is stored outside ASP.NET worker process in SQL Server database. Location of this database is represented by sqlConnectionString attribute.

Now, let’s take a look at session storage internals.

We access Session data through a property named Session. This Session property is exposed by System.Web.HttpContext class and System.Web.UI.Page. (Every ASP.NET page is converted in a class which derives from Page class.) This Session property is an object of HttpSessionState class in System.Web.SessionState namespace as shown above.

HttpSession object has a private member _dict of type SessionDictionary (namespace System.Web.SessionState) as shown below:

C#
private SessionDictionary _dict;

SessionDictionary is an internal class which derives from NameObjectCollectionBase.

The relationship is depicted in a small class diagram:

SessionDictionary relationship

The most important piece of the session state management puzzle is a HttpModule called SessionStateModule. This HttpModule talks to session state providers and hydrates HttpSessionState for each HTTP request. This HttpModule is listed in your machine.config file in <httpModules> section.

I reproduced part of this section from machine.config file from my computer, for reference:

XML
<httpModules>
<add name="OutputCache" type="System.Web.Caching.OutputCacheModule"/>
<add name="Session" type="System.Web.SessionState.SessionStateModule"/>
.
.
.
</httpModules>

For every HTTP request to your page in your ASP.NET application, an object of type HttpWorkerRequest is created and is served by an instance of HttpApplication class. (For complete discussion of HTTP Pipeline model, check URLs mentioned in References.)

During the processing of this request, InitModules() method of HttpApplication class is called.

Figure 3 below depicts the entire call sequence:

call graph

Inside InitModules(), all the modules listed under <system.web>/<httpModules> section are initialized, i.e., Init method of each of these HttpModules is called, i.e.. Init method of SessionStateModule is called. In the Init method of SessionStateModule, session state settings are read from <system.web>/<sessionState> section of web.config file of your ASP.NET application, and then it calls another method InitModuleFromConfig. The signature of this method is listed below:

C#
private void InitModuleFromConfig(HttpApplication app, 
                                     Config config, bool configInit);

The parameter app represents the instance of HttpApplication class that is being used to serve the HTTP request.

InitModuleFromConfig adds various event handlers for session management related events that are raised from InitInternal() method of HttpApplication.

Table below shows which EventHandlers in SessionStateModule are tied to which events of HttpApplication class.

Table : HttpApplication Events handled  by the SessionStateModule EventHandlers
EventEventHandlers
AcquireRequestStateBeginAcquireState, EndAcquireState
ReleaseRequestStateOnReleaseState
EndRequestOnEndRequest

Please note that, at this point, the session state data has not been acquired. There is one more important thing that happens after the above mentioned EventHandlers are tied. Based on attribute values settings of <system.web>/<sessionState> section in your ASP.NET application's config file, the session state provider is tied to SessionStateModule.

All the session state providers implement the interface IStateClientManager.

Table below shows the type of object used to manage state based on value of the mode attribute of sessionStateTag:

Session State Provider based on mode attribute of <System.web>\<sessionState>
modeClass Handling Session State
InProcInProcStateClientManager
StateServerOutOfProcStateClientManager
SQLServerSqlStateClientManager

This session state provider or StateClientManager is stored in a private variable of SessionStateModule.

Once Init() method of SessionStateModule returns control to InitInternal method of HttpApplication, processing continues and AcquireRequestState event is raised.

It is at this point that session state is actually acquired. When this event is raised, the event handler (BeginAcquireState) in SessionStateModule which was tied earlier is called which then calls GetSessionStateItem of SessionStateModule which then asks StateClientManager to get the session state.

In order to judge the performance difference, we will look into each of these StateClientManagers and see how the session data is actually stored and retrieved. For this and more, stay tuned for Part II.

References:

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
AnswerRe: Unable to find _dict property there??? Pin
MichaelElliott24-Feb-06 9:15
MichaelElliott24-Feb-06 9:15 
GeneralLack of information Pin
Sebastian P.R. Gingter30-Jan-05 20:39
Sebastian P.R. Gingter30-Jan-05 20:39 
GeneralRe: Lack of information Pin
LyphTEC2-Feb-05 18:46
LyphTEC2-Feb-05 18:46 
GeneralRe: Lack of information Pin
AbbasHere19-Aug-09 7:51
AbbasHere19-Aug-09 7:51 
GeneralGreat Article Pin
Prasad Khandekar3-Aug-04 20:37
professionalPrasad Khandekar3-Aug-04 20:37 
GeneralGreat Article, needs better formatting Pin
ronnyek3-Aug-04 12:33
ronnyek3-Aug-04 12:33 
GeneralRe: Great Article, needs better formatting Pin
Mandeep S Bhatia3-Aug-04 12:47
Mandeep S Bhatia3-Aug-04 12:47 
GeneralRe: Great Article, needs better formatting Pin
AbbasHere19-Aug-09 7:52
AbbasHere19-Aug-09 7:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.