Session State in ASP.Net

This article explains in detail the Session State Management technique and its modes in ASP.Net.

Let us start from the very beginning. Let"s first try to understand why we need to maintain the state of our application or why we need State Management. As we all know, our web is "Stateless", in other words a new instance of a web page class, is recreated each time the page is posted to the server. HTTP is a stateless protocol and it can't hold the client information on the page. For example, if the user inserts some information on one page and then moves to the next page then that inserted data will be lost from the first page and moreover the user will not be able to retrieve that information.

So basically here we need someone to hold the state of our application. Here is the privitage role of our "session state". Basically a session is a variable used between the client and the server that is stored on the server side. Now it can be stored either on an Internet Information Service (IIS) server that is by default our "inproc" mode or it can be stored in a state or SQL Server that is our "outproc" mode. We will discuss both, the inproc and outproc modes in detail later in the article.
So a session helps to maintain the user state and data all over the application by storing the information on the server memory. Also a session can store any kind of information or object on the server side and is accessible in the entire website.
Now let's discuss the entire scenario that happens when the user state and data is maintained using session state. First of all when the user requests a new application or page, first the "Application" start event fires in the get state and that application object is sharable in the entire website. After the application life cycle, the session start event fires for the specific user in the get state but when some other user again requests that page, no application start event will fire, only the session start event in the post state will fire for that specific user. Every object is stored in the application on the basis of the Key value. We can see both the application and session start up events by adding a "Global.asax" file in our project.
The process of maintaining the session state proceeds in the following manner. First the client hits the website and the information is stored in the session. Then a Session table will be made by default on the IIS server and in the session IDs of all the users visiting the website will be stored by the server. Now the next time the client requests some information with the unique session ID from the server, the server looks in the session providers and retrieves the serialized data from the state server and type casts the object. 

Now let us see how to store and retrieve values in a session.


The following code is used for storing a value in a session:
  1. // Storing Username in session.Session[ "UserName" ] = txtUser.Text;  
  2. // Retreiving  
  3. values  
  4. from  
  5. session.// Check whether session variable null  
  6. or not if(Session[ "UserName" ] != null) { // Retreiving UserName  
  7. from  
  8. session lblWelcome.text = "Welcome: +Session[" UserName "];  
  9. }  
  10. else  
  11. {  
  12. //Do something else  
  13. }  
As we know all these values will be stored and retreived from the session on the IIS server by default.
Now for maintaining the load balance we need to free the IIS server. So we require an "Outproc" mode of the session state. Now we will study both the "Inproc" and "Outproc" modes of the session state in detail.


This is the default session mode in ASP.Net. It stores the information in a memory object in the current application domain. So it is easily and quickly available and is best suited for web application performance but the main disadvantage is that because all the information is stored on the server side in the same application domain, if we will restart the server all the data will be lost. When the client requests data, the State Provider reads the data from an in-memory object and return it to the client. In web.config, we need to specify the session mode and also set the time out.


  • It stores session data in a memory object of the current application domain. So accessing data is very fast and data is easily available.
  • There is not a requirement for serialization to store the data in InProc session mode.
  • Implementation is very easy, similar to using the ViewState.

Although an InProc session is the fastest, common and default mechanism, it has many limitations as in the following:
  • If the worker process or application domain is recycled, all session data will be lost.
  • Though it is the fastest, more session data and more users can affect performance, because of memory usage.
  • We can't use it in Web Garden scenarios.
  • This session mode is not suitable for web Farm scenarios.
As in the preceding discussion, we can conclude that InProc is a very fast session storing mechanism but suitable only for small web applications. InProc session data will be lost if we restart the server, or if the application domain is recycled. It is also not suitable for Web Farm and Web Garden scenarios.

Now we will have a look at the other options available to overcome these problems. First is the StateServer mode.


This is also called Out-Proc session mode. StateServer uses a stand-alone Windows Service that is independent of IIS and can also be run on a separate server. This session state is totally managed by aspnet_state.exe. This server may run on the same system, but it's outside of the main application domain where your web application is running. This means if you restart your ASP.NET process, your session data will still be alive. This approache has several disadvantages due to the overhead of the serialization and de-serialization involved, it also increases the cost of data access because every time the user retrieves session data, our application hits a different process.

Configuration for StateServer session mode

In StateServer mode, session data is stored in a separate server that is independent of IIS and it is handled by aspnet_state.exe. This process is run as a Windows Service. You can start this service from the Windows MMC or from the command prompt.

By default, the "Startup Type" of the ASP.NET state service is set to Manual; we need to set it to Automatic.
From the command prompt, just type "net start aspnet_state". By default, this service listens to TCP port 42424, but we can change the port from the Registry editor as shown in the picture below:
Now have a look at the web.config configuration for the StateServer setting. For the StateServer setting, we need to specify the stateConnectionString. This will identify the system that is running the state server. By default, stateConnectionString uses IP (localhost) and port 42424.
  1. <configuration>  
  2.     <system.web>  
  3.         <sessionstate mode="StateServer"    time out="30" stateConnectionstring="tcpip="  
  4. "tcpip=localhost:42424"  </sessionstate>  
  5.     </system.web>  
  6. </configuration>    

inproc and outproc mode in session state differences using code

Now let"s us try to understand the difference between inproc and outproc mode in session state using code. 
  1. Open Visual Studio then create a new project. Select Web - ASP.Net Empty Web Application and let's name it "OutofProcSessionState".
  2. Add new Web Form Login.aspx as in the following:
    • Add a new TextBox to get the username and a button to Login as in:

  3. Login.aspx
    Enter User Name:
    1. <asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>  
    2. <asp:Button ID="btnSubmit" runat="server" Text="Go to Home Page" OnClick="btnSubmit_Click"/>  
    Login.aspx.cs: Add the handler code for the Submit button in the code behind
    as in the following:
    • Store the User Name logged in by user in the session indexed by User Name.
    • Redirect the user to the Home Page on click of the button.
    1. protected void btnSubmit_Click(object sender, EventArgs e)  
    2. {  
    3.    Session["UserName"] = txtUserName.Text.ToString();  
    4.    Response.Redirect("Home.aspx");  
    5. }  
    • Add a new Web Form, Home.aspx:
      1. Home.aspx: Add a label control in the Home Page to show the logged in User Name
    1. <label id="lblUserName" runat ="server"></label>  
    • Home.aspx.cs: In the Page Load event retrieve the User Name from the Session State.
      • Retrieve the User Name from the Session and display it.
        • If the User Name is not present in the session then show the user name as Anonymous User.
      1. protected void Page_Load(object sender, EventArgs e)   
      2. {  
      3.     if (Session["UserName"] != null && Session["UserName"] != "")   
      4.     {  
      5.         lblUserName.InnerText = Session["UserName"].ToString();  
      6.     }   
      7.     else   
      8.     {  
      9.         lblUserName.InnerText = "Anonymous User";  
      10.     }  
      • Run the application with Login.aspx as the Start Page.
      • So in the output we will find the UserName in the home page.
      • So all is fine here so far since we are working by default in inproc mode and the session data is stored by default on the IIS server.
      • Now let us stop our web development server and restart it again. Here we will find that all our session data is lost that was stored on the IIS server.
      • So here we will be requiring the State Server mode in which all the session data will be stored on a seperate server or Windows service that is totally independent of IIS and is managed by ASP.Net_state.exe as I said above.
      I hope my article is useful for all those who are new in the field of ASP.Net and finding their future in the ASP.Net domain. Session State is quite useful for the purpose of interviews. In my next article I'll be describing SQL Server outproc mode of session state. I have tried my best to summarize Session State, still if anyone has questions then please provide me your valuable suggestions.

      Similar Articles