In my previous article State Management in Asp.Net I have explained about various states of ASP.NET and in this article, I am going to explain you about Session State. Session State is one of the important state management variables in ASP.NET. It works on the server side.

A session is defined as the period of time that a unique user interacts with a Web application. When a new user begins to interact with the application, a new session ID is generated and associated with all subsequent requests from that same client and stored in a cookie on the client machine.

Advantage of session state is that once you store your data in session and access that data from anywhere in the application across multiple pages. The advantage of session state over cookies is that session can store any type of data as well as complete dataset whereas cookies can store only a small amount of data.

Session state is maintained in an instance of the HttpSessionState class and is accessible through the Session property of both the Page and HttpContext classes. It is not necessary for you to instantiate the Session Object. An instance is automatically provided for you.

When you use session then session create a cookie on the browser that name is Asp.Net_SessionId to detect the correct user to provide associated information across multiple pages. Session state store user information on Web server not on browser like cookies.

Create Session

A new session can be created by specifying session name in a session variable. For example, in below code, we are creating a new session that name is UserName. In this session, we are storing simply a string value Asphelps. You can store any type of object data in session state.

Session["UserName"] = "qawithexperts";

Read Session Value

Once you created session then, you can retrieve stored object in session from anywhere in the application. Use below code to retrieve your session data from any page in the application.

if (Session["UserName"] != null)
{
     string userName = Session["UserName"].ToString();
}

Session End

You can stop the user session at any time in the application. You have three option to stop user session.

  1. Abandon - End user session in the application.
  2. Remove - Remove a particular session in the application.
  3. Clear - Clear all session object.
// Remove UserName session
Session.Remove("UserName");

// End a user session
Session.Abandon();

//Clear all session items
Session.Clear();

Control Session Timeout

When you are using session then the session will expire after a specific time. This time is known as session timeout. Default session timeout value is 20 minutes. But you can increase session timeout using session's TimeOut property by declaring on a page or in Web.Config.

<system.web>
    <sessionState timeout="60" />
</system.web>

Disable Session

If you want to disable session then you can disable session from a page or from Web.Config.

On page directive use EnableSessionState to false.

<%@ Page CodeFile="Default2.aspx.cs" Inherits="Default2" EnableSessionState="False" %>

In Web.Config file set session mode Off.

<system.web>
    <sessionState mode="Off" />
<system.web>

Session Property

Session state has the following properties:

Property Description
CookieMode Enable to you to specify whether cookieless sessions are enabled.
TimeOut Enable to specify session timeout in minutes.
SessionID Retrieve unique session id.
IsNewSession Check session is new one or not
Count Retrieve total session items from session state.
IsReadOnly Check session is read-only or not
IsCookieless Check whether the session is cookieless or not.
Keys Retrieve all session items from session state.

Let's take a look on a complete example of creating session and checking it's key values, for that create a ASP.NET project in your Visual studio, by navigating to  File->New->Project -> Select "ASP.NET Web Project"-> Name it and Click "OK"

Create the Default.aspx page(if it is not created by template) & use the below C# code related to sessions.

 protected void Page_Load(object sender, EventArgs e)
    {
        //creating session
        Session["UserName"] = "qawithexperts";
        //retrieve session value
        if (Session["UserName"] != null)
        {
            string userName = Session["UserName"].ToString();
        }
        //check Session Id
        string id = Session.SessionID;

        //check session timeout
        int timeOut = Session.Timeout;
        //session mode
        HttpCookieMode mode = Session.CookieMode;

        //session count
        int total = Session.Count;

        //check cookieless or not
        bool isCookieless = Session.IsCookieless;

        //check if Session is new or previosuly used
        bool isNewSession = Session.IsNewSession;

        //check if Session is readOnly
        bool isReadOnly = Session.IsReadOnly;

        //get all sessions keys
        foreach(var key in Session.Keys)
        {
            Response.Write(key);
        }
    }

Debugging the above code gives output as below

state-management-in-asp-net-min.gif

Session Configuration

You can set all session properties in Web.Config

<system.web>
  <sessionState
   cookieless="false" mode="InProc" timeout="60"
   regenerateExpiredSessionId="true" />
<system.web>

Session Mode

Session state stores session data in multiple location that depends on session mode. You should know about session mode, so that you can use appropriate mode to store session data. Session have followings modes:

Mode Description
InProc Session state stores session data on web server. This is default value.
Off Disable session state in the application
Custom Session state stores session data on custom storage location.
SqlServer Session state stores session data in sql server database.
StateServer Session state stores session data on separate process Session disable form page.

Cookieless Session

Session state internally uses cookies to store user information. Asp.Net framework uses Asp.Net_SessionId cookies to identify user, so that specific user information associate with correct user.

Every browser providing cookies enable disable facilities. Suppose if any user disables their cookies on browser then session state does not work. In that condition you can take advantage of cookieless session that store user session Id in page url instead of cookies. So you session is working even if cookies is disabled from browser.

Its look likes below url:

http://localhost:52844/(X(1)S(4twxndy2u23wygzfrtjjxl0s))/Default.aspx

For enable cookieless session, you have specify in Web.Config. Use cookieless attribute of sessionstate in Web.Config.

Value Description
AutoDetect Session state stores session ID in cookie when cookies enable on browser otherwise its add session ID in page url.
UseCookies Always session state stores session ID in cookies.
UseDeviceprofile Session state stores session ID in cookie when cookies enable on browser otherwise its add session ID in page url.
UseUri Always session state stores session ID in page url

We suggest you that use autoDetect, because its add session Id in page url when cookies disabled on browser otherwise its uses cookies.

Use regenerateExpiredSessionId for better security purpose.

<system.web>
    <sessionState cookieless="AutoDetect" regenerateExpiredSessionId="true" />
<system.web>

Session Event

Session State have two events that raised in global.asax

  • Session_Start
  • Session_End

Session_Start fires after whenever a new session is starts in the application and Session_End fires after whenever session abandoned or expired.

void Application_Start(object sender, EventArgs e) 
{
 Application["TotalSession"] = 0;
}

void Session_Start(object sender, EventArgs e) 
{
 Application.Lock();
 int count = Convert.ToInt32(Application["TotalSession"]);
 Application["TotalSession"] = count + 1;
 Application.UnLock();
}

void Session_End(object sender, EventArgs e) 
{
 Application.Lock();
 int count = Convert.ToInt32(Application["TotalSession"]);
 Application["TotalSession"] = count - 1;
 Application.UnLock();
}

We used Lock and UnLock application object because multiple user could potentially access the same item in the application state at the same time.

Reference