Introduction To ASP.NET Sessions

Background

We all know that the web uses the HTTP protocol and the HTTP protocol is a stateless protocol; in other words, when a client sends a request to the server, an instance of the page is created and the page is converted to HTML format and then the server provides the response and then the instance of the page and the value of the control are destroyed. So if we have a requirement to store the values of the controls and pass them into another web form then a State Management Technique is used.

Introduction

Session is a State Management Technique. A Session can store the value on the Server. It can support any type of object to be stored along with our own custom objects. A session is one of the best techniques for State Management because it stores the data as client-based, in other words the data is stored for every user separately and the data is secured also because it is on the server.



Now here I am explaining sessions with an example.

Step 1: Open Visual Studio 2010.

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



Step 3: Now click on Solution Explorer.



Step 4: Now right-click on the "Add" -> "New Item" -> "Web Form" and add the name of the web form and I had added 2 Web Form1.aspx and Web Form2.aspx.



Step 5: After adding the web form the following code is added to Web Form1.aspx.

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Session.WebForm1" %>  
  2.   
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  4. <html xmlns="http://www.w3.org/1999/xhtml">  
  5. <head id="Head1" runat="server">  
  6.     <title></title>  
  7. </head>  
  8. <body>  
  9.     <form id="form1" runat="server">  
  10.     <div>  
  11.         User Name:-<asp:TextBox ID="tbUserName" runat="server"></asp:TextBox>  
  12.         <br />  
  13.         <br />  
  14.         Password:-<asp:TextBox ID="tbpwd" runat="server"></asp:TextBox>  
  15.         <br />  
  16.         <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" />  
  17.     </div>  
  18.     </form>  
  19. </body>  
  20. </html> 

And the code is:

  1. protected void Button1_Click(object sender, EventArgs e)  
  2. {  
  3.     //textbox value is stored in Session  
  4.     Session["UserName"] = tbUserName.Text;  
  5.     Session["Pwd"] = tbpwd.Text;  
  6.     Response.Redirect("WebForm2.aspx");  

And then add the following code to Web Form2.aspx.

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="Session.WebForm2" %>  
  2.   
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  4. <html xmlns="http://www.w3.org/1999/xhtml">  
  5. <head id="Head1" runat="server">  
  6.     <title></title>  
  7. </head>  
  8. <body>  
  9.     <form id="form1" runat="server">  
  10.     <div>  
  11.         User Name:-<asp:TextBox ID="tbUserName" runat="server"></asp:TextBox>  
  12.         <br />  
  13.         <br />  
  14.         Password:-<asp:TextBox ID="tbpwd" runat="server"></asp:TextBox>  
  15.         <br />  
  16.     </div>  
  17.     </form>  
  18. </body>  
  19. </html> 

And the code of the code behind is:

  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.     //Session value is assign on the text box  
  4.     if (Session["UserName"] != null)  
  5.     {  
  6.        tbUserName.Text = Session["UserName"].ToString();  
  7.     }  
  8.     if (Session["Pwd"] != null)  
  9.     {  
  10.        tbpwd.Text = Session["Pwd"].ToString();  
  11.     }  

Now to set the session we need to use a config file. We can set the session on one of the following 2 types of configuration files:

  1. Machine Configuration file: Machine Configuration is applied for all application.
  2. Application Configuration file: It's applied for only application by application basis.

The following is the configuration of the Web.config file:

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

Output





Session Events

There are 2 type of events available in ASP.NET. We can handle both sessions in a global.asax file.

  1. Session_Start(): When the new session is initialized then the session_start event is raised.
  2. Session_end(): When the session is Expires then the Session_End event raised.

Session Mode

In ASP.NET there are 4 types of Session Mode.

Off: We can disable the session mode for the entire application using the off mode.



1. InProc

The InProc Session mode is the default Session Mode. Using this Session Mode the Session Mode is stored in the application worker process (aspnet_wp.exe) in the application domain. The Worker Process is dependent on the IIS server version. The memory location was handled by the ASP.NET worker thread. It only involves a considerable overhead for the worker thread to manage these. Also, since this is in the memory of server, chances are that large session information would lead to more memory usage and thus lowering the performance.
I had explained by an example the use inproc session mode.

In Inproc Session mode the important point is:

1. When we get the WebForm2 then if we end the task of aspnet_wp.exe from the Task Manager and then again reload the WebForm2 then you will get no output, that means that all the sessions are stored in a worker process and after closing the task the session will be lost.

The following are the advantages of the InProc mode:

  1. Inproc session mode is very easy to impement, the only thing that is required is sessionState mode="InProc".
  2. It will perform fast becaue the session is kept on the web server within the ASP.NET Worker Process.
  3. Data is stored saparetly and the data is secure so it is suitable for web applications.
  4. In this mode there is no need to serialize and deserialize the object for storage and retrieval of the data.

The following are the disadvantages of InProc mode:

  1. Session data is lost when the worker process or application process is recycled.
  2. Not Suitable for WebFarms and and WebGardens: In a webFarm that the web application is deployed on the various web servers.



    If the client sends the request and the request goes to the server load balancer and then it sees which Web Server is needed to be used, for example if the Web Server1 is needed to be used then the request goes to WebServer1 and the session variable is stored in Web Server1 and if we refresh web form2 and again make a request to Web Form2 then the server load balancer sends the request to web server2 and the session variable is not stored in Web Server2 so the session variable is lost. So the InProc mode is dependent on the Web Server.
  3. Increase the load of server

    In Session Mode the sessions are stored on the web server. If the number of sessions are increased then the load of the server is also increased and the scalability could be an issue.

2. StateServer

These is also the Out-Proc Session mode. StateServer uses a stand-alone Windows Service that is independent on IIS and can also be run on a separate server. This session state is totally managed by aspnet_state.exe. And the Session Variables are stored in an ASP.NET State service.

Now configure with the ASP.NET State Service.

Step 1: Go To Start and from there go to "Run" and type "services.msc" as in the following:



Step 2: Now open the Services Management Window and right-click on ASP.NET State Service and start the service; by default these services are stopped.



Step 3: For configuration with web.config write the code to web.config file.

  1. <sessionState mode="StateServer" stateConnectionString="tcpip=localhost:42424">  

Generally the state services and web services are not in the same machine of a dedicated server so for the connection we need to write the stateConnectionString and here we need to provide the IP address or the name of the machine where the state service is running and here my services are run on localhost and 42424 is the port number.

The ASP.NET State Services can be present on a Web Server or a dedicated machine. So if we closed the worker Process (aspnet_wp.exe) then it is also not affected.



When the client sends a request to the web server, the web server stores the session data on the state server. The StateServer may be the current system or a different system. But it will be totally independent of IIS. The destination of the StateServer will depend on the web.config stateConnectionString setting. If we set it to localhost:42424 then it will store data in the local system itself. For changing the StateServer destination, we need to change the IP and ensure aspnet_state.exe is up and running on that system. Otherwise you will get the following exception while trying to store data on the session.

Advantage of State Service

  1. No issue about Worker Process because it's not dependent on Worker Process.
  2. Can be used with Web Farm and Web Garden: It supports a Web Farm and Web Garden both



    When a client sends a request of WebForm1.aspx then the server load balancer checks which server needs to the used and if the request goes to web server1 then web server sees the request store the session on the state server and again provides the response of WebForm2.aspx and now if the client again sends a request of webform2 and the load balancer provides the request to web server2 and then web server2 has the web.config file and it sends a request to the state server and the state server already has a session so it provides the response.
  3. Scalability is also increased because it keeps data separate from IIS.

Disadvantage of State Service

  1. Performance Decrease

    When the request goes to the server the object is serialized and deserialized so for that the performance is decreased so it is slower than the OnProc State Mode.
  2. If the request goes to the server and for some reason the ASP.NET State Service is restarted then all the sessions will be destroyed.


3. SQLServer

In thee mode the session data is stored inside the SQL Server database so to store the sesion in the database we need to follow these steps.

Step 1: From the command prompt, go to your Framework version directory,  for example: c:\windows\microsoft.net\framework\<version>. and search for the aspnet_regsql.exe that in which version these files are present and execute the file in the command prompt.



Parameter Description:

  1. ssadd:Add support for SQLServer mode session state.
  2. sstype p:P stands for Persisted. It persists the session data on the server.
  3. S : Server name.
  4. U :User name.
  5. P :Password.
  6. E :Authentication using the windows credential of the currently logged on users.

Step 2: After executing the command, open the database:



Step 3: Now for configuration we need to write the connection string in the web.config file:

<sessionState mode="SQLServer" sqlConnectionString="Server=DIVS\SQLEXPRESS;Integrated Security=true">

Step 4: And the webfrom1.aspx and webform2.aspx code are the same.

Step 5: Now after sending a request to the server open the database and here the session id is stored and by default its expiration time is 20 minutes.



The following are the advantages of SQLServer mode:

  1. SQL Server is a more reliable and secure option.
  2. It's not dependent on the Worker Process and ASP.NET State Service so if it restarts then it is also not affected by the session.
  3. It is useful for a Web Farm and Web Garden: it is the same as State Server mode. It works the same also, the only difference is that the session is stored on the SQLServer Database.



  4. Scalability: The scalability is increased compared to InProc and State Server because the session is stored in the database, no matter how many requests on the web server.

The following are the disadvantages of SQLServer mode:

  1. It's slower than StateServer and InProc Session mode.
  2. It must be serialized and deserialized.

The following are the reasons to use the SQLServer Session mode:

  1. When we need a sesssion with more secrity, in other words we need that the data of the session is more secure.
  2. If there happens to be frequent server restarts, this is an ideal choice.
  3. We can use SQLServer session mode when we need to share sessions between two different applications.

According to performance and durability the difference between InProc,State Server and SQL Server is:

Session mode Performance Durability
InProc more(1 processor and 1 server) less
State Server Medium(n processor and 1 server) Medium
SQL Server Less More

4. Custom

Using this session mode we can control everything, like session id and all it means that you can create your own algorithm to create a session id. It uses less something compared to others. You can create your own session state provider for example: Oracle.

The method of the implement of the custom session mode is:



Step 1: The initialize method sets the custom provider and provides the connection with the provider.
Step 2: SetItemExpireCallback is used to set the expiration time.
Step 3: InitializeRequest is called on every request and CreateNewStoreData is used to create a new instance of SessionStateStoreData.

Now configure with the web.config file as in the following:

  1. <sessionState mode="Custom" customProvider="demo">  
  2.   <providers>  
  3.      <add name="demo" type="CustomDataType" />  
  4.   </providers>  
  5. </sessionState> 

The following are the advantages of custom session mode:

  1. We can use an existing table for storing the session data
  2. It's not dependent on IIS.

The following are the disadvantages of custom session mode:

  1. Processing of data is very slow

The following is when should we use should use a custom control:

  1. When we want to create our own session id.
  2. Where we want to store session data in other location
  3. When we need to use an existing table to store session data.

Cookie less session

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

Now by taking a previous example if we give the request to the server of webForm1.aspx and store the cookies and give the response and here go to the browser and right-click on the browser and go to inspect element or press F12.



Here this is the Session Id that was stored in the cookies, it will never change if we run webForm1 or WebForm2 because for a specific client or browser it is unique. But if by default cookies are disabled on the client machine then we need to configure it in the web.config file as in the following:

  1. <sessionState mode="InProc" cookieless="true"> </sessionState> 

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




Both the session ids are the same and if we change the session id from the URL and refresh the page it goes to the server and the server thinks that the request comes from a different user so it never provides the required output.

Remove Session

Mostly we can remove session using one of the following 4 methods:

  1. Session.Remove(strSessionName):- Removes an item from the session state collection
  2. Session.RemoveAll():- Removes all items from the session collection.
  3. Session.Clear():- it is same as sesion.RemoveAll() method.
  4. Session.Abandon():-Cancels the current session.

Enable and Disable Sessions

We can enable and disable session state in one of two ways:

  1. Page Level: We have the attribute of page level that EnableSessionState
    1. <%@ Page Language="C#" EnableSessionState="False" 
    It is 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.
    1. <%@ Page Language="C#" EnableSessionState="ReadOnly" 
  2. Application Level: Disables a Session for an entire web application; we need to use this at the applicationlevel. Set the property EnableSessionState in Web.Config.
    1. <pages enableSessionState="false"></pages> 

The following are the advantages of session:

  1. It is easy to implement.
  2. Store data separately.
  3. Session is secure and transparent from the user.

The following are the disadvantages of session:

  1. Performance decrease if we not use InProc Sesion mode.
  2. Overhead involved in serializing and de-serializing session data.

Up Next
    Ebook Download
    View all
    Learn
    View all