Click here to Skip to main content
Email Password   helpLost your password?

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:

<sessionState 
    mode="InProc"
    stateConnectionString="tcpip=127.0.0.1:42424"
    sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes"
    cookieless="false" 
    timeout="20" />
Attribute Option Description
mode   Specifies where to store the session state.
  Off Disables session state management.
  InProc Session state is stored locally in memory of ASP.NET worker process.
  StateServer Session state is stored outside ASP.NET worker process and is managed by Windows service. Location of this service is specified by stateConnectionString attribute.
  SQLServer Session 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:

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:

<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:

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
Event EventHandlers
AcquireRequestState BeginAcquireState, EndAcquireState
ReleaseRequestState OnReleaseState
EndRequest OnEndRequest

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>
mode Class Handling Session State
InProc InProcStateClientManager
StateServer OutOfProcStateClientManager
SQLServer SqlStateClientManager

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:

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralMy vote of 1
amarjeetyadav
9:28 27 Jun '09  
very poor
GeneralProblem with my session variables
maheshvzx
19:19 13 Mar '08  
Hello,

I am very new to .net. I am storing my user id as session. But unfortunately its changing the session when multiple users logged in.

If ABC logged in with his user name and password and XYZ logged in after that the profile of XYZ is changing to ABC's one. So, the session is changing from one to another.

Please help me to solve this problem.

Thanks and regards,

mahesh

analochaka

GeneralThanks for Nice Article
Chirag R Darji
1:55 18 Apr '07  
Thanks for Nice Article.

Chirag Darji
Team Lead (MCP)
http://chiragrdarji.wordpress.com

GeneralUnable to find _dict property there???
Himadrish Laha
22:04 11 Sep '05  
On your article you had written there as below:

"[[

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

private SessionDictionary _dict;

]]"


Now, I did not find any such property _dict under "Class HttpSessionState". I search by the name _dict, still no luck to get it.

Am I missing something or YOU Smile ).



Himadrish Laha
GeneralRe: Unable to find _dict property there???
Mike Elliott
10:15 24 Feb '06  
You won't find it. As stated in the article, it's private. Since it's private you will neither be able to see it or use it.

If you just want to see that there really is a private property named SessionDictionary use a utility like ILDASM or Reflector to disassemble and look into the library, otherwise you will not see the property. Also, since the property name is SessionDictionary, your search should have been for the property name and not the private memory backing field.

Hope this helps you a little. D'Oh!
GeneralLack of information
PhoenixHawk
21:39 30 Jan '05  
Hi,

I personally think that this article lacks of important information.
A beginner does not want nor need to know how the call stack looks like before session data is retrieved from the asp.net service itself.

A beginner (like me) needs to know, what he has to do that session information is saved at all. You say, session information can be stored in a SQL server. Nice. Do I need to setup the tables for that by myself? If yes, how do they have to look like. Or are the tables created the first time a session is started and the tables are not there?

How can I configure how long a session may be active before it times out?
What is best: Saving data in SQL or in memory or out of process? Where is the data stored if I configure that option?

What data can I store in that session? How much data may be kept there?

All that are questions that are important to a beginner, but none of them was answered. I personally think this article is not very helpful to a ASP.net beginner.

Sorry for that really severe criticism, but thats my opinion after all.

GeneralRe: Lack of information
LyphTEC
19:46 2 Feb '05  
Hi,

I think u can find most of all the information you are after in the References section. This article is delving into the depths of the ASP.NET Session management, hence the title. So the info here is targetted at that aim.

Cheers..
GeneralRe: Lack of information
Fazal Abbas
8:51 19 Aug '09  
This post is about internals of ASP.NET Session. If you are not looking for this information because you are beginner or some other reason then its not the author's problem. He explained well and discussed the topic according to heading.

He gave you pointers to think and not "how to design" as this is not the topic.

Cheers
GeneralGreat Article
Prasad Khandekar
21:37 3 Aug '04  
Hello,

Thank's a lot for posting such a nice article. I am waiting for the part 2.

Regards,

Prasad P. Khandekar
Knowledge exists, man only discovers it.
GeneralGreat Article, needs better formatting
ronnyek
13:33 3 Aug '04  
Lots of information ,but lots of broken images and text wrapping off the right side of the page.
GeneralRe: Great Article, needs better formatting
MandeepS
13:47 3 Aug '04  
This is my first artcle submission. I played with Html and try to fix this, will try to do better formatting in next article.Smile
GeneralRe: Great Article, needs better formatting
Fazal Abbas
8:52 19 Aug '09  
It looked fine to me. I'm a Firefox user.


Last Updated 3 Aug 2004 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010