Session Management in ASP.Net

Web is stateless, which means a new instance of a web page class is re-created each time the page is posted to the server. As we all know, HTTP is a stateless protocol, it can't hold client information on a page. If the user inserts some information and move to the next page, that data will be lost and the user would not be able to retrieve that information. What do we need here? We need to store information. Session provides a facility to store information on server memory. It can support any type of object to store along with our own custom objects. For every client, session data is stored separately, which means session data is stored on a per client basis.

State management using session is one of the best ASP.NET features, because it is secure, transparent from users, and we can store any kind of object in it. Along with these advantages, sometimes session can cause performance issues in high traffic sites because it is stored in server memory and clients read data from the server. Now let's have a look at the advantages and disadvantages of using session in our web applications.



Following are the basic advantages and disadvantages of using session. I have describe in details with each type of session at later point of time.

Advantages:
  • It helps maintain user state and data all over the application.
  • It is easy to implement and we can store any kind of object.
  • Stores client data separately.
  • Session is secure and transparent from the user.
Disadvantages:
  • Performance overhead in case of large volumes of data/user, because session data is stored in server memory.
  • Overhead involved in serializing and de-serializing session data, because in the case of StateServer and SQLServer session modes, we need to serialize the objects before storing them.

Storing and retrieving values from Session

Storing and retrieving values in session are quite similar to that in ViewState. We can interact with session state with the System.Web.SessionState.HttpSessionState class, because this provides the built-in session object in ASP.NET pages.
The following code is used for storing a value to session:

//Storing in Session
Session["FirstName"] = FirstNameTextBox.Text;
Session["LastName"] = LastNameTextBox.Text;

//Check weather session variable null or not
if (Session["LastName"] != null)
{
//Retrieving UserName from Session
       lblWelcome.Text = "Welcome : " + Session["LastName"];
}
else
{
      //Do Something else
}

Another example of retrieving object from session:

// When retrieving an object from session state, cast it to the appropriate type.
ArrayList stockPicks = (ArrayList)Session["StockPicks"];
 
// Write the modified stock picks list back to session state.
Session["StockPicks"] = stockPicks;


Session ID
ASP.NET uses a 120 bit identifier to track each session. This is secure enough and can't be reverse engineered. When a client communicates with a server, only the session ID is transmitted between them. When the client requests for data, ASP.NET looks for the session ID and retrieves the corresponding data. 

Session Mode and State Provider

In ASP.NET, there are the following session modes available:
  •  InProc
  • StateServer
  • SQLServer
  • Custom
  • Off


If we set session Mode="off" in web.config, session will be disabled in the application. For this, we need to configureweb.config the following way:

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

InProc Session Mode
This is the default session mode in ASP.NET. Its stores session information in the current Application Domain. This is the best session mode for web application performance. But the main disadvantage is that, it will lose data if we restart the server. 



In web.config, we have to mention the session mode and also set the timeout.

<system.web> 
<sessionState mode="InProc" timeout=”30” />
</system.web> 

The above session timeout setting keeps the session alive for 30 minute.

Advantages and disadvantages

Advantages:

  •  It store 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 requirement of serialization to store data in InProc session mode.
  • Implementation is very easy, similar to using the ViewState.

Disadvantages:

Although InProc session is the fastest, common, and default mechanism, it has a lot of limitations:


  •  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.

We can conclude that InProc is a very fast session storing mechanism but suitable only for small web applications. InProc session data will get lost if we restart the server, or if the application domain is recycled.

StateServer Session Mode

This is also called Out-Proc session mode. StateServer uses a stand-alone Windows Service which 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 approaches 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 which is independent of IIS and it is handled byaspnet_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 have 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 show 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 used the IP 127.0.0.1 (localhost) and port 42424.
<sessionState mode="StateServer"
stateConnectionString="tcp=127.0.0.1:42424"
stateNetworkTimeout="40"/>

When we are using StateServer, we can configure the stateNetworkTimeOut attribute to specify the maximum number of seconds to wait for the service to respond before canceling the request. The default timeout value is 10 seconds.
For using StateServer, the object which we are going to store should be serialized, and at the time of retrieving, we need to de-serialize it back. I have described this below with an example.

How the StateServer Session Mode works

We use the StateServer session mode to avoid unnecessary session data loss when restarting our web server. StateServer is maintained by the aspnet_state.exe process as a Windows service. This process maintains all the session data. But we need to serialize the data before storing it in StateServer session mode.



As shown in the above figure, 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 127.0.0.1:42424, it will store data in the local system itself. For changing the StateServer destination, we need to change the IP, and make sure aspnet_state.exe is up and running on that system.

When we are storing an object on session, it should be serialized. That data will be stored in the StateServer system using the State Provider. And at the time of retrieving the data, the State Provider will return the data. The complete flow is given in the picture below:


Advantages and Disadvantages

Advantages:


  • It keeps data separate from IIS so any issues with IIS will not hamper session data.
  • It is useful in web farm and web garden scenarios.

Disadvantages:


  • Process is slow due to serialization and de-serialization.
  • State Server always needs to be up and running.

SQLServer Session Mode

This session mode provides us more secure and reliable session management in ASP.NET. In this session mode, session data is serialized and stored in A SQL Server database. The main disadvantage of this session storage method is the overhead related with data serialization and de-serialization. It is the best option for using in web farms though.



To setup SQL Server, we need these SQL scripts:

  • For installing: InstallSqlState.sql
  • For uninstalling: UninstallSQLState.sql

These files would found at:
system drive\Windows\Microsoft.NET\Framework\version\



The easiest way to configure SQL Server is using the aspnet_regsql command.

When should we use SQLServer Session Mode?


  • SQL Server session mode is a more reliable and secures session state management.
  • It keeps data in a centralized location (database).
  • We should use the SQLServer session mode when we need to implement session with more security.
  • If there happens to be frequent server restarts, this is an ideal choice.
  • This is the perfect mode for web farm and web garden scenarios (I have explained this in detail later).
  • We can use SQLServer session mode when we need to share session between two different applications.

Configuration for SQLServer Session Mode

In SQLServer session mode, we store session data in SQL Server, so we need to first provide the database connection string in web.config. The sqlConnectionString attribute is used for this.
After we setup the connection string, we need to configure the SQL Server. I will now explain how to configure your your SQL Server using the aspnet_regsql command.

Step 1: From command prompt, go to your Framework version directory (system drive\Windows\Microsoft.NET\Framework\version\

Step 2: Run the aspnet_regsql command with the following parameters:
aspnet_regsql -S Ct30\sql2005 -U sa -P ct30 -ssadd -sstype p


Parameters
Description
-ssadd
Add support for SQLServer mode session state.
-sstype p
P stands for Persisted. It persists the session data on the server.
-S
Server name.
-U
User name.
-P
Password.

After you run the command, you will get the following message:




Step 3: Open SQL Server Management Studio, check if a new database ASPState has been created, and there should be two tables and some stored procedures:
·         ASPStateTempApplications
·         ASPStateTempSessions




Change the configuration string of the StateServer example and run the same sample application.
Just store the roll number and user name and click on the Submit button. Open the ASPStateTempSessions table from SQL Server Management Studio.


Advantages and Disadvantages

Advantages:


  • Session data not affected if we restart IIS.
  • The most reliable and secure session management.
  • It keeps data located centrally, is easily accessible from other applications.
  • Very useful in web farms and web garden scenarios.

Disadvantages:


  • Processing is very slow in nature.
  • Object serialization and de-serialization creates overhead for the application.
  • As the session data is handled in a different server, we have to take care of SQL Server. It should be always up and running.


Hope, you wil enjoy.... :)

Comments

Popular posts from this blog

Data Bound Controls in ASP.Net - Part 4 (FormView and DetailsView controls)

ASP.net: HttpHandlers

The Clickjacking attack and X-Frame-Options