ASP.NET Session Management

ASP.NET Session Management

Table of Contents

State management is implemented to retain information about user requests. Web pages are stateless. Each request creates a new page without containing any previous information about the user requests. ASP.NET supports several State Session management techniques to maintain state information.

State management in ASP.NET is classified as:

  1. Client-side state management: When we use client-side state management, the state-related information will directly get stored on the client-side. That particular information travels back and communicate with every request generated by the user and then respond to server-side communication.
  2. Server-side state management: Server side state management is different from client-side state Session management, but the operations and working are the same. In server-side state management, all the information gets stored in the user memory, and because of this functionality, more secure domains are available at the server-side than client-side state management.
Image 4

Client-side state management techniques are:View State: This is used for storing user data in ASP.NET. Sometimes, users want to maintain or keep their data temporarily after a postback. Here, VIEW STATE is the most used and preferred way, and this property is enabled by default, but we can manually change it according to ourfunctionality. We need to change EnableViewState value to either TRUE for enabling it or FALSE for opposite operation.

  • Hidden field: This is used for storing a small amount of data on the client-side. In most simple words, it is just a container that contains some objects, but their result does not get displayed on our web browser and is invisible in the browser. It stores only one value for the single variable, and it is the preferable way when a variable’s value changes frequently, but we do not need to keep track of that every time in our application or web program.
  • Cookies: This is a small text file stored in users hard drive using the client’s browser. Cookies are only used for the sake of user’s identity matching as it only keeps information like sessions ids, some frequent navigation, or postback request objects. When we connect to the internet for accessing a particular service, that cookie file gets retrieved from our hard drive via the browser for identifying users. The access of cookie depends upon the life cycle of the expiration of that particular cookie file.

Cookies are of two types:

  1. Persistent Cookie: Cookie having an expiration date is called a persistent cookie, and these cookies reach their end as their expiration dates come to an end. In this cookie, we can set an expiration date.
  2. Non-Persistent Cookie: Non-persistent cookie doesn’t get stored in the client’s hard drive permanently and maintains the user information when the user accesses or uses the services. It is simply the opposite procedure of a persistent cookie.
  • Control State: Control state is based on a custom control option. For expected results from CONTROL STATE, we enable the property of view state.
  • Query Strings: These are used for some specific purpose. In the general case, these are used for holding some value from a different page and move these values to a different page. The information stored in it can easily navigate from one page to another or the same page.

Server-side state Session management techniques are:

  • Session State: Session is an essential technique to maintain state. Usually, the session is used to store information and identity. The server stores information using Sessionid.

Session State modes are of five types:

  1. InProc mode: This stores session state in memory on the Web server.
  2. StateServer mode: This stores session state in a separate process called the ASP.NET state service and ensures that session state is preserved if the Web application is restarted and makes session state available to the multiple Web servers in a Web form.
  3. SQLServer mode: This stores session state in a SQL Server database and ensures that session state is preserved if the Web application restarts and makes session state available to multiple Web servers in a Web form.
  4. Custom mode: This enables you to specify a custom storage provider.
  5. Off mode: This disables the session state.

Application State

Application State is a server-side management state. It is also called application-level state Session management. In this main store, user activity in server memory and application event is shown in Global.asax file.

A Session is a State Management technique that is used to store and retrieve the values of a user. A session is one of the best approaches for State Management because it stores the data separately for every user, and the data is also secured because it is on the server.

For example, you have a page with two text boxes, one for the username, and the other for the password. When you click on the Submit button available on that page, the application will store the username and password values and will pass and display it on the next page.

Now let’s understand this with an example.

Step 1: Open Visual Studio.

Step 2: Click on New Project > WEB > ASP.NET Empty Web Application.

https://www.c-sharpcorner.com/UploadFile/225740/introduction-of-session-in-Asp-Net/Images/Session%20in%20ASP.NET.jpg

Step 3: Click on Solution Explorer.

https://www.c-sharpcorner.com/UploadFile/225740/introduction-of-session-in-Asp-Net/Images/Session%20in%20ASP.NET1.png

Step 4: Right-click on Add > New Item > Web Form. Specify the name of the web form. Here we have added two forms WebForm1 and WebForm2.

https://www.c-sharpcorner.com/UploadFile/225740/introduction-of-session-in-Asp-Net/Images/Session%20in%20ASP.NET2.jpg

Step 5: Add the code to WebForm1.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Session.WebForm1" %>    
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
<html xmlns="https://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title></title>  
</head>  
<body>  
    <form id="formSubmit" runat="server">  
    <div>  
        User Name:-<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>  
        <br />  
        <br />  
        Password:-<asp:TextBox ID="txtpwd" runat="server"></asp:TextBox>  
        <br />  
        <asp:Button ID="btnSubmit" runat="server" OnClick="Button1_Click" Text="Submit" />  
    </div>  
    </form>  
</body>  
</html>
The code behind it is:
protected void Button1_Click(object sender, EventArgs e)  
{  
    //textbox value is stored in Session  
    Session["UserName"] = txtUserName.Text;  
    Session["Pwd"] = txtpwd.Text;  
    Response.Redirect("WebForm2.aspx");  
}

Step 6: Add the code to WebForm2.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="Session.WebForm2" %>    
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
<html xmlns="https://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title></title>  
</head>  
<body>  
    <form id="formSubmit" runat="server">  
    <div>  
        User Name:-<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>  
        <br />  
        <br />  
        Password:-<asp:TextBox ID="txtpwd" runat="server"></asp:TextBox>  
        <br />  
    </div>  
    </form>  
</body>  
</html>
The code behind it is:
protected void PageLoad(object sender, EventArgs e)  
{  
    //Session value is assign on the text box  
    if (Session["UserName"] != null)  
    {  
       txtUserName.Text = Session["UserName"].ToString();  
    }  
    if (Session["Pwd"] != null)  
    {  
       txtpwd.Text = Session["Pwd"].ToString();  
    }  
}

Step 7: Now set the session in Web.config file.

<system.web>  
<sessionState mode="SQLServer" sqlConnectionString="Server=DIVS\SQLEXPRESS;Integrated Security=true"></sessionState>  
<compilation debug="true" targetFramework="4.0" />  
</system.web>

Output:

https://www.c-sharpcorner.com/UploadFile/225740/introduction-of-session-in-Asp-Net/Images/Session%20in%20ASP.NET3.PNG
https://www.c-sharpcorner.com/UploadFile/225740/introduction-of-session-in-Asp-Net/Images/Session%20in%20ASP.NET4.PNG

Cookieless Session

The session id is stored on the client machine as a cookie and then used by the webserver to identify if the request is coming from the same user or a different user.

Considering the previous example, if we give the request to the server of WebForm1.aspx, store the cookies, and give the response and then go to the browser, right-click on the browser, and open inspect element or press F12.

https://www.c-sharpcorner.com/UploadFile/225740/introduction-of-session-in-Asp-Net/Images/Session%20in%20ASP.NET16.jpg

The above image shows the Session-Id that was stored in the cookies. It will not change if we run WebForm1 or WebForm2 because it is unique for a specific client or browser. If cookies are disabled by default on the client machine, then we need to configure it in the web.config file:

<sessionState mode=”InProc” cookieless=”true”> </sessionState>

Moreover, if we run the WebForm1, then we will get the session id in the URL, and it is then sent back between the client and the Web Server with every request and response.

https://www.c-sharpcorner.com/UploadFile/225740/introduction-of-session-in-Asp-Net/Images/Session%20in%20ASP.NET17.PNG
https://www.c-sharpcorner.com/UploadFile/225740/introduction-of-session-in-Asp-Net/Images/Session%20in%20ASP.NET18.PNG

Both the session ids are same, and if we change the session id from the URL and refresh the page, it will go to the server, and the server will think that the request is coming from a different user, so it never provides the required output.

Remove Session:

We can remove the session using one of the below methods:

  • Session.Remove(strSessionName): It will remove an item from the session state collection.
  • Session.RemoveAll(): It will remove all items from the session collection.
  • Session.Clear(): It is same as sesion.RemoveAll() method.
  • Session.Abandon(): It will cancel the current session.

Enable and Disable Sessions:

A Session can be enabled and disabled by the following ways:

  1. Page Level: We have the attribute of page-level that EnableSessionState

<%@ Page Language=”C#” EnableSessionState=”False” 

It disables the session state.

We can make it read-only also. This will permit access to session data but will not allow writing data on the session.

<%@ Page Language=”C#” EnableSessionState=”ReadOnly” 

  1. Application Level: Disables a Session for an entire web application; we need to use this at the application level. Set the property EnableSessionState in Web.Config.

<pages enableSessionState=”false”></pages> 

  1. You can also set the Off mode in the sessionState of the web.config file, in this way it will disable the session of the application.

<sessionState mode=”Off”/>

Advantages of Session

  • It is easy to implement.
  • It stores data separately.
  • The Session is always secure and transparent from the user.

Disadvantages of Session

  • Performance decrease if we are not using InProc Session mode.
  • Overhead is involved in serializing and de-serializing session data.

Share this article
Subscribe
By pressing the Subscribe button, you confirm that you have read our Privacy Policy.
Need a Free Demo Class?
Join H2K Infosys IT Online Training
Enroll Free demo class