Asp.Net Session State Management

Tarun Kumar Chatterjee
 
Net – Technology Specialist
April 9, 2017
 
Rate this article
 
Views
3797

In this article let me explain you in simple language and step-by-step details about the concept of Session state management in Asp.Net.

Web applications run on HTTP protocols and this HTTP protocol is stateless in nature, meaning it does not remember state or retain any state between requests and responses.

Here the state management techniques are relevant since they provide a way to remember/retain values between client calls to the server.

Various state management techniques

Client-side State Management:

· View State

· Hidden Field

· Cookies

· Control State

· Form

Server-side State Management:

· Session

· Application Object

· Caching

I am going to explain only the Session State in this article.

Whenever the user requests a web form from a web application it will get treated as a new request. An ASP.NET session will be used to store the previous requests for a specified time period. Session state data is shared across all the web pages, in other words when navigating from one page session the data would available.

Here are the various session modes available in ASP.NET. 

  • InProc
  • StateServer
  • SQLServer

I have created a sample Asp.Net application which will have two pages

Default.aspx page code:

 <%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="AspDotNetSessionStateManagement._Default" %>
 
 <asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
     <div>
     <asp:Label ID="lblSessionValue" runat="server" Text="Session Value"></asp:Label>
     </div>
     <p></p>
 
    <div>
        <asp:Button ID="btnSetSession" runat="server" Text="Set Session" OnClick="btnSetSession_Click" />
        <asp:Button ID="btnRedirect" runat="server" Text="Redirect" OnClick="btnRedirect_Click" />
    </div>
 
 </asp:Content>
 

Default.aspx.cs page code:

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Web;
 using System.Web.UI;
 using System.Web.UI.WebControls;
 
 namespace AspDotNetSessionStateManagement
 {
     public partial class _Default : Page
     {
         protected void Page_Load(object sender, EventArgs e)
         {
             if (!IsPostBack)
             {
                 if (Session["Counter"] == null)
                 {
                     Session["Counter"] = 0;
                 }
                 lblSessionValue.Text = "Session Value: " + Session["Counter"].ToString();
             }
         }
 
         protected void btnRedirect_Click(object sender, EventArgs e)
         {
             Response.Redirect("RedirectedSessionPage.aspx");  
         }
 
         protected void btnSetSession_Click(object sender, EventArgs e)
         {
             if (Session["Counter"] != null)
             {
                 int SessionCounter = (int)Session["Counter"] + 1;
                 lblSessionValue.Text = "Session Value: " + SessionCounter.ToString();
                 Session["Counter"] = SessionCounter;
             }  
         }
     }
 }
 

RedirectedSessionPage.aspx Page Code:

 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="RedirectedSessionPage.aspx.cs" Inherits="AspDotNetSessionStateManagement.RedirectedSessionPage" %>
 
 <!DOCTYPE html>
 
 <html xmlns="http://www.w3.org/1999/xhtml">
 <head runat="server">
     <title></title>
 </head>
 <body>
     <form id="form1" runat="server">
     <div>
      <div>
     <asp:Label ID="lblSessionValue" runat="server" Text="Session Value"></asp:Label>
     </div>
     
     </div>
     </form>
 </body>
 </html>
 

RedirectedSessionPage.aspx.cs page code:

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Web;
 using System.Web.UI;
 using System.Web.UI.WebControls;
 
 namespace AspDotNetSessionStateManagement
 {
     public partial class RedirectedSessionPage : System.Web.UI.Page
     {
         protected void Page_Load(object sender, EventArgs e)
         {
             if (Session["Counter"] != null)
             {                
                 lblSessionValue.Text = "Session Value: " + Session["Counter"].ToString();                 
             }  
         }
     }
 }
 

InProc Mode:

InProc mode can be done in an ASP.NET web application using a configuration file by setting the mode attribute in the element SessionState.

In Web.config within <system.web> add the below configuration:

 <sessionState mode="InProc" customProvider="DefaultSessionProvider" cookieless="true">

When Inproc session state is used the session variables are being stored on the web server memory inside the ASP.NET worker process.

Advantages of InProc: 

  • Easy to Implement.
  • Complex Objects can be added without serialization.
  • Best in performance compared to out-of-process modes.

Disadvantages of InProc:

  • Not able to sustain the session values when the worker process/IIS is restarted
  • Scalability is a major problem i.e. in web farm or Web garden.
  • Not good for applications with a large user base.

StateServer Mode:

Go to Run then enter “Services.msc” then Start ASP.NET State Service.
By default ASP.NET state service is in manual mode.

clip_image002

StateConnectionstring basically consists of the following;
Server/system: where an ASP.NET Windows service is running.
Port: By default the state service listens to the TCP port 42424 that is configurable using the registry.

In Web.config within <system.web> add the below configuration:

 <sessionState mode="StateServer" customProvider="DefaultSessionProvider" stateConnectionString="tcpip=localhost:42424">

Here in my example I am using my machine’s Windows service to implement the state server mode. It could be a separate dedicated machine or a web server in the network depending on requirements.
So now the session state variables are stored in a Widows service of my machine so the recycling process of the ASP.NET worker process does not have any impact on the session variables.
Advantages of State Server Mode: 

  • Worker process recycling does not impact session variable data
  • Can be stored on the same web server or different dedicated machine

Disadvantage of State Server Mode:

  • Restart of sate service could lead to session data loss.
  • Slower than in proc mode

SQL Server Session Mode

When the Session mode of an ASP.NET application is set by SQL Server then the session variables are being stored in the SQL Server database.

At the location “C:\Windows\Microsoft.NET\Framework64\v4.0.30319” aspnet_regsql. exe is present.

To configure SQL Server session state first we need to run the utility by using the following commands which will create a database ASPState with some Tables and Stored procedures.

clip_image003

Execute the query to fetch the data from newly created database. Initially tables will be empty.

clip_image005

 

 

In Web.config within <system.web> add the below configuration:

 <sessionState mode="SQLServer"  customProvider="DefaultSessionProvider"  sqlConnectionString="Data Source=TARUN-PCSQLSERVER;integrated security=SSPI" timeout="1000">

Now run the application

Session state will be starting store into the database

Execute the same query into the database and we will see the session data stared storing.

clip_image007

Advantages of SQL Server Mode

  • Very secure and most reliable option for the session management.
  • Session data will be able to survive after worker process restart or state window service restart.
  • Most suited for web garden or web farm type deployments

Disadvantages of SQL Server mode

  • Slow performance
  • Overhead for serialization and deserialization

Hope this will help you to understand about the different Session states mode, their implementations, advantages & disadvantages.

 

Happy Coding

Tarun Kumar Chatterjee

Category : Office 365, SharePoint

Author Info

Tarun Kumar Chatterjee
 
Net – Technology Specialist
 
Rate this article
 
Tarun has been working in IT Industry for over 12+ years. He holds a B-tech degree. He is passionate about learning and sharing the tricks and tips in Azure, .Net ...read more
 

Leave a comment