How to correctly use sessions in ASP. NET, asp. netsession

Source: Internet
Author: User
Tags object serialization

How to correctly use sessions in ASP. NET, asp. netsession

The Session object is used to store the information required by a user to access a specific aspx page from the moment the user leaves. When you switch the page of an application, the variables of the Session object are not cleared.
For a Web Application, the content of the Application object accessed by all users is identical, while the content of the Session object accessed by different users is different. Session can save the variable. This variable can only be used by one user. That is to say, each browser has its own Session object variable, that is, the Session object is unique.

What is Session?

The Web is stateless and provides a new method: each time a user submits a request to the server, a new webpage is rendered. As we all know, HTTP is a stateless protocol that cannot be connected to clients through pages. If the user needs to add some information and jump to another page, the original data will be lost and the user will not be able to recover the information. Why do we need this? We need to save the information! Session provides a solution for saving information on the server. It can store all types of objects and user object information as objects. Sessions are stored independently for each client. This means that Session data stores the basic information of each client. See:

Each client has an independent Session.

Session-based state management is one of the best features of ASP. NET, because it is secure, transparent to clients, and can store any type of objects. In addition to these advantages, Session may sometimes cause performance problems for websites with high performance requirements. Because it consumes the server's memory to store the data the user needs to access the website, let's take a look at the advantages and disadvantages of Session for your Web application.

Advantages and disadvantages of Session

Next we will discuss the advantages and disadvantages of using Session in general cases. I will describe the usage situation of each Session.


It can help maintain user statuses and data throughout the application.

It allows us to simply store any type of objects.

Store client data independently.

For users, sessions are secure and transparent.


Because the Session uses the server memory, it will become a performance bottleneck when a large number of users are involved.

In the process of serialization and deserialization, it will also become a performance bottleneck, because in the StateServer (Status Service) in the mode and SQL server mode, we need to serialize and deserialize the stored data.

In addition, the various Session modes have their own advantages and disadvantages. Next we will discuss various Session modes.

Read/write sessions

Reading/writing sessions is very simple. Just like using ViewState, we can use System. web. sessionState. httpSessionState class to interact with the Session. This class is in ASP. NET page. The following code uses Session for storage:

//Storing UserName in SessionSession["UserName"] = txtUser.Text;

Next let's look at how to read data from the Session:

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

We can also store other objects. The following example shows how to store a DataSet to a Session.

//Storing dataset on SessionSession["DataSet"] = _objDataSet;

The following code shows how to read DataSet from a Session.

//Check weather session variable null or notif (Session["DataSet"] != null){    //Retrieving UserName from Session    DataSet _MyDs = (DataSet)Session["DataSet"];}else{    //Do Something else}


MSDN (read the session variable section)

Session ID

ASP. NET uses a 120bit identifier to identify each Session. This is a safe and irreversible design. When the client communicates with the server, the Session ID needs to be transmitted between them. When the client sends request data, ASP. NET searches for Session IDs and retrieves data through Session IDs. Perform the following steps:

The client clicks the website and the client information is stored by the Session.

The server creates a unique Session ID for the client and stores this ID on the server.

The client sends a request with SessionID to obtain the information stored on the server.

The Server obtains serialized data from the State Server through the Session Provider and forcibly converts the data type to an object.

The following figure shows the process:

Communication between clients, Web servers, and Session providers


SessionID in MSDN

Session mode and Session Provider

In ASP. NET, the following Session modes can be used:





Each Session State has a Session Provider. The following figures show their relationships:

Session state system diagram

We can select from these basic Session State providers. When ASP. NET receives an information request with a Session ID, the Session State and its corresponding Provider provide and store the corresponding information. The following table shows the Session mode and Provider name:

Session State mode State Provider
InProc In-memory object (built-in object)
StateServer Aspnet_state.exe
SQLServer SQL Server Database
Custom Custom provider

In addition, there is another mode: "OFF". If we select this option, the Session will not be able to provide services for this application. However, our goal is to use Session, so we will discuss the above four Session modes.

Session States

In the Session State mode, all Session configurations and maintenance are handed over to the Web application. Session State itself is a big thing. It basically means that all your Session configurations, whether web. config or page back-end code, are true. The element in web. config is used as the Session configuration. In the element, Mode, Timeout, StateConnectionString, and CustomProvider can be configured. We have discussed the connection strings of each part. Before we discuss Session mode, we will briefly describe the following Session events:

Session event

There are two Session events available in ASP. NET:



You can handle these two events in the application in the global. asax file. When a new Session is enabled, the session_start event is triggered. When the Session is recycled or expired, Session_End is triggered:

void Session_Start(object sender, EventArgs e) {    // Code that runs when a new session is started} void Session_End(object sender, EventArgs e) {    // Code that runs when a session ends. }


Application and Session Events

Session Mode

We have already discussed the Session mode. Next we will talk about the differences between these modes:






If we set the Session Mode = "off" in web. config, the Session will be unavailable in the application. Its settings are as follows:

InProc Session mode:

This is the default Session mode of ASP. NET. It stores Session information in the current application domain. This is the best Session mode. But his biggest drawback is that Session data will be lost when we restart the service. The InProc mode has some advantages and disadvantages. Next we will detail these points.

InProc Overview:

As we have already said, Session data in InProc mode will be stored in the current application domain, so it is the easiest, fast, and easy to use.

In InProc mode, Session data is stored in a collection object in the application domain. It works in an application pool. If we restart the service, we will lose Session data. Normally, the client sends a request, and the State Provider reads data from the memory object and returns the data to the client. In web. config, we must provide the Session mode and set the expiration time:

In the above settings, the expiration time of the Session is set to 30 minutes, which can also be configured in the background code.


There are two Session events in ASP. NET that can be used: Session_Start () and Session_End (). This mode (backend code control) only supports Session_End () events. This event is called when the Session times out. Generally, the InProc Session mode is as follows:

The Session_End () event is called when the Session expires. InProc is a very fast processing mechanism because there is no serialized read/write process and data is stored in the same domain.

When should we use the InProc mode?

InProc is the default Session mode. It is very suitable for small applications and applications with a small number of users. We should try to avoid Web Garden and Web Farm) use him in a situation (I will talk about this situation later)

Advantages and disadvantages:


The Session data is stored in the current application, so data access is fast, simple, and efficient.

In InProc mode, objects do not need to be serialized for storage.

It is very simple to use, just like ViewState.


Although InProc is the fastest, most common, and default mechanism, it has many restrictions:

If the application process is recycled, all Session data will be lost.

Although he is the fastest, when the Session data is too large and there are too many users, he will affect the performance of the entire program due to the large use of memory.

We cannot use this mode in the Web garden environment.

This mode is not suitable for Web Farm environments.

Now let's take a look at other available methods to circumvent these shortcomings. The first is the StateServer mode:

StateServer Session Mode

StateServer mode Overview

This is also called the Out-Proc Session mode. StateServer uses an independent Windows Service to provide the Session service. It is independent of IIS and can also use only one server. The stateserverservice is provided by aspnet_state.exe. This service can also run with your application service on the same server. Note that it is a service independent of the Web application domain. This means that the Session data still exists after you restart your Web service. The disadvantage of this solution is that there is a performance bottleneck: Data Reading and Writing requires serialization and deserialization. Because it is not the same application domain, it also increases the performance consumption of Data Reading and writing, because they are two different processes.

Configure StateServer Session Mode

In StateServer mode, Session data is stored in a service independent of IIS. This process runs as a Windows service. You can start it in the Windows Service Manager (MMC) or command line.

By default, ASP. NET StateServer (Chinese name: ASP. NET Status Service) is enabled manually by default and must be set to automatic.

If you want to start from the command line, you only need to enter "net start aspnet_state". By default, this service listens to TCP port 42424, but we can change this setting in the registry,

Now let's take a look at the StateServer settings in web. config. In the StateServer settings, we need to specify the StateServer connection string stateConnectionString: pointing to the system running StateServer. By default, StateConnectionString uses IP127.0.0.1 (localhost) Port 42424.

When StateServer is used, we can also set the timeout stateNetworkTimeOut feature to specify the number of seconds to wait for the service response, that is, the time interval between the event that sends the request and cancels the response. The default value is 10 seconds.

When StateServer is used for storage, the object will be serialized for storage, and when the object is read, the data will be deserialized. Let's take a look at the following example:

How StateServer works

StateServer is used to avoid unnecessary Session data loss when the Web service is restarted. Stateserveris maintained by the aspnet_state.exe process as a service. This process maintains all Session data, but we need to serialize the data before it is stored in StateServer.

As shown in, when the client sends a request to the Web server, the Web server stores Session data in StateServer, And the StateServer may be in the current system or in another system, however, it must be independent from IIS. to implement it, we must. config to configure stateConnectionString. For example, we set to point to The slave runs normally on this system, and then when you need to read and write the Session (that is, a wrong point is caused by modifying the IP address ), you will cause this exception:

When we store an object to the Session, the object will be serialized. The system uses the State Provider to store data in StateServer. When reading data, the State Provider returns the data. The complete flowchart is shown below:

Example of StateServer Session mode:

This is a simple example of using the StateServer Session mode. I directly created this example in IIS to easily understand its usage:

Step 1: Open Visual Studio> File> New> website. Select HTTP as the web application location.

Now that you open IIS, you will see a virtual directory named StateServer in my example.

Step 2: create a simple UI: it will get the role number and name of a student, and we will save the name and number to the StateServer Session. I will also create a class: StudentInfo, which is defined as follows:

[Serializable]public class StudentInfo{    //Default Constructor    public StudentInfo()    {           }    ///    /// Create object of student Class    ///    ///Int RollNumber    ///String Name    public StudentInfo(int intRoll, string strName)    {        this.Roll = intRoll;        this.Name = strName;    }     private int intRoll;    private string strName;    public int Roll    {        get        {            return intRoll;        }        set        {            intRoll = value;        }    }     public string Name    {        get        {            return strName;        }        set        {            strName = value;        }    }}

Now let's look at the backend code. I have added two buttons: one is to save the Session, and the other is to get the Session:

protected void btnSubmit_Click(object sender, EventArgs e){    StudentInfo _objStudentInfo =       new StudentInfo(Int32.Parse( txtRoll.Text) ,txtUserName.Text);    Session["objStudentInfo"] = _objStudentInfo;    ResetField();}protected void btnRestore_Click(object sender, EventArgs e){    StudentInfo _objStudentInfo = (StudentInfo) Session["objStudentInfo"];    txtRoll.Text = _objStudentInfo.Roll.ToString();    txtUserName.Text = _objStudentInfo.Name;}

Step 3: configure the StateServer of your web. config. As described earlier, make sure that the State Server on the Server to which the configuration points is enabled and running.

Step 4: run the application.

Enter data and click Submit.

In the next test, I will explain how to use StateServer

First, remove the [Serializable] feature of the StudentInfo class and run the application. When you click the Submit button, you will see the following error:

Clearly states that you must serialize your objects before they are stored.

2. Run the program. After you click the Submit button to save the data, restart IIS.

In InProc, I promise that your Session data will be lost, but in StateServer, click the Restore Session button and you will get your original data, because StateServer data does not depend on IIS, it saves data independently.

Third, stop the StateServer service in the Windows Service Manager (MMC). Click the Submit button and you will see the following error:

Because your StateServer process is not running, remember these three points when using StateServer.

Advantages and disadvantages

Based on the above discussion:


StateServer runs independently of IIS, so no matter what problems occur in IIS, it does not affect StateServer data.

It can be used in the Web Farm and Web Garden environments.


Serialization and deserialization are required to slow down the speed.

StateServer must ensure normal operation.

I will stop StateServer here, and you will see more interesting points in Server Load balancer, such as Web Farm and Web Garden.


State Server Session Mode

ASP. NET Session State

SQL Server Session Mode

SQL Server Mode Overview

ASP. NET Session mode provides us with enhanced security and reliability. In this mode, Session data is serialized and stored in an SQL Server database, the disadvantage of this mode is that the read/write mode that requires Session serialization and deserialization has become the main performance bottleneck and is the best choice for Web Farm.

To set SQL Server, we need these SQL scripts:

Installation: InstallSqlState. SQL

Uninstall: UninstallSQLState. SQL

The simplest configuration method is to use the aspnet_regsql command.

I have explained how to configure it before. This is the most useful method for State management in the web Farm mode.

Why do we use the SQL Server mode?

The SQL Server Session mode provides safer and more reliable Session management.

It ensures that data is stored in a centralized environment (database ).

When we need to implement sessions more securely, we should use the SQL Server mode.

If the server needs to be restarted frequently, this is a perfect solution.

This is a perfect solution for web Farm and web Garden (I will explain it in detail later ).

When we need to share sessions between two applications, we need to use the SQL Server mode.

Configure the SQL Server Session Mode

In SQL Server mode, our data is stored in SQL Server. Therefore, we must first provide the database connection string in web. config. sqlConnectionString is used to do this.

After configuring the connection string, We will configure SQL Server. Here we will demonstrate how to use the aspnet_regsql command to configure the database.

Step 1: Go to the command line and enter the Framework version directory E. g.: c: \ windows \ \ framework \.

Step 2: run the aspnet_regsql command with parameters.

The following describes how to use parameters:

Parameters Description
-Ssadd Added the SQLServer mode session state.
-Sstype p P persistence. store the data persistently in the database
-S Server Name
-U User Name
-P Password.

After running, you can see the following information:

The configuration is complete.

Step 3:

Open SQL Server and view the ASPState database. There will be two tables:



Change the connection string in the settings to create an application as in the StateServer example.

When you click Submit, save the Roll Number and user name, open the database, and enter the ASPStateTempSessions table. This is the Session data you saved:

Now let's discuss the following issues in the StateServer mode:

1. Remove the Serialize feature (keyword) from the StydentInfo class)

2. Restart IIS to read Session data.

3. Stop the SQL Server service

I think I have already explained these issues clearly in StateServer.

(Note: the first will cause the object to be unable to be serialized, and an exception will be thrown, the second will not be affected, and the third will be affected when the database service is disabled, restarting the Database Service will retrieve the data in the Session because it is stored persistently .)

Advantages and disadvantages


Session data is not affected by IIS restart

The most reliable and secure Session Management Mode

It centrally stores Session data locally to facilitate access by other applications

It is very useful in the Web Farm and Web Garden scenarios.


Compared with the default mode, it will appear very slow

Object serialization and deserialization will become performance bottlenecks

To access SQL Server on different servers, we must ensure the stable operation of SQL Server.


Read more about SQLServer mode

Custom Session Mode

Generally, we use the InProc, StateServer, and SQL Server modes. However, we still need to know about the User-Defined Session mode. This is a very interesting Session mode, because all user sessions are controlled by us, and even Session IDs, you can generate Session IDs by writing algorithms by yourself.

You can easily develop a custom Provider from the base class SessionStateStoreProviderBase. You can also generate a SessionID by implementing the ISessionIDManager interface.

Is the process of processing a custom method:

In the Initialize method, we can set a custom Provider. It will be provided to the Provider to initialize the connection. SetItemExpireCallback is used to provide SessionTimeOut (Session expired). When the Session expires, we can register a method for calling. InitializeRequest is called when a request is initiated. CreateNewStoreData is called when a SessionStateStoreData (Session data storage class) instance is created.

When do we use the custom Session mode?

1. When we want to store Session data in a database other than SQL Server.

2. When we must use an existing (specific) table to store Session data.

3. When we need to use a custom SessionID

How do I configure the custom Session mode?

We need to perform the following configuration in web. config:

For more information about the custom mode, see references.

Advantages and disadvantages:


1. We can use an existing table (specified table) to store Session data. This is useful when we use a previously used database.

2. It runs independently of IIS, so restarting the server does not affect it.

3. We can establish our own Session ID logic to allocate Session IDs.


1. Data Processing is slow.

2. Creating a custom Session Status Provider is a basic (low-level) task. It must handle various situations and ensure data security.

I recommend that you use third-party providers instead of writing a set of providers.


Custom Mode

Production deployment Overview:

Deploying our applications in a production environment is a great challenge for a Web developer. Because in a large production environment, a large amount of user data needs to be processed, it is difficult to load such a huge amount of data to a server. This concept comes from the use of Web Farm, Web Garden, and Server Load balancer.

A few months ago, I deployed an actual environment that handles access from millions of users and over 10 domain controllers, server Load balancer is equipped with more than 10 servers and service databases. For example, Transaction Server and LCS server. The biggest challenge lies in Session management across multiple servers. A simple image is displayed for this production environment:

I will try to explain and let you remember different application scenarios.

Application pool

This is the most important thing when you create an actual production environment. The application pool is used in IIS to separate applications of different working processes. The application pool can separate our applications for better security, reliability, and effectiveness. Applications in the application pool are not affected when a process is faulty or recycled on the server.

Role of the application pool:

Application pool configuration roles are an important security measure in IIS6 and IIS7. Because when an application accesses a resource, it specifies the identity of the application. In IIS7, there are three predefined authentication methods, which are the same as IIS6.

Application pool role Description
LocalSystem An account built on the server to manage permissions. It can access local and remote resources. For files or resources on any server, we must set the application identity to LocalSystem.
LocalServices Built-in local authentication. It cannot access any network.
NetworkServices This is the default identity of the application pool, and NetworkServices is a verified Local User Account permission.

Create and specify an application pool

On the IIS Management page, right-click the application pool directory and choose create

Give the application pool an ID and click OK.

Right-click a virtual directory (the StateServer site I am using) and assign the StateServerAppPool to the StateServer virtual directory.

Now the StateServer site runs in a specified independent application pool StateServerAppPool. No other application will affect this program. This is the main advantage of an independent application pool.

Web Garden

Every application pool is running in an independent workflow (w3wp.exe ). We can allocate multiple processes to a single application pool, and one application pool runs multiple processes. This situation is called Web Garden ), multiple worker processes a single application can have better output performance and less time in many cases. Each worker process has its own thread and memory space.

As shown in, there will be multiple application pools in IIS, and each application pool has at least one working process, and one Web Garden will have multiple working processes.

In your applications, the use of Web parks will inevitably have a constraint: if we use the InProc mode, our applications will not work correctly, because the Session will work in different processes. To avoid this problem, we will use the OurProc Session mode. We can use the State Server or SQL Server Session mode.

Main advantages:

The Worker Process in the Web Park shares requests to each process. If a process crashes, other processes can still work normally and continue to process the requests.

How to create a Web Garden?

Right-click the program pool and choose Performance ?) Tab-> select Web Garden Section

His value is 1 by default, and now he is changed to a number greater than 1.

How to specify a Session in the Web garden?

I have explained that the InProc mode is to process objects in a single worker process and store objects in the process. Now, if we want to process multiple processes, Session processing will become very difficult, because each worker process excludes its own memory. If the first request data is sent to WP1 and the Session data is saved, and the second request is sent to WP2, I will not be able to correctly obtain the Session data. If the value is set to WP2, an exception will be thrown. Therefore, do not use InProc mode in Web Garden mode.

We use StateServer or SQLServer mode to handle this situation. We have previously explained that these two modes do not depend on the worker process, as mentioned in the previous example, When IIS is restarted, you can still access Session data.

Session Mode Recommended or not
InProc No
StateServer Yes
SQLServer Yes

Web Farm and Server Load balancer

This is the most common situation in the production environment. When you need to deploy your application on multiple servers, the main reason for using this mode is to balance the load to multiple servers, A server Load balancer is used to distribute loads to multiple servers.

We can see that when a client sends a request through a URL, it first goes to the Server Load balancer and then distributes the request to the server through the Server Load balancer. The Server Load balancer distributes the request among different servers.

How can we deal with our sessions?

Process sessions in the case of WEB Farm and Server Load balancer

Processing sessions in Web Farm is a challenging task.

InProc: InProc Session mode. Session data is stored in the worker process as objects. Each server will have its own worker process and keep Session data in the memory.

If a server goes down, the request will access other servers, but there is no Session data in other servers. Therefore, the InProc mode is not recommended for the Web Farm scenario.

State Server: I have explained how to use and configure the StateServer mode. In the WebFarm environment, you will understand how important it is, because all Session data will be stored in one location.

Remember, in the web Farm environment, you must ensure that you have the same section on all your web servers. Other configurations are consistent with those described earlier. the config file must have the same Configuration Attribute (stateConnectionString) in the Session State.

SQL Server: This is another choice, which is also the best choice in the Web Farm environment. We need to configure the database first. The following steps have been mentioned before.

As shown in, all Session data on the web Server will be stored in an SQL Server database. Remember that in StateServer mode and SQL Server mode, you will serialize and store objects. When a Web server fails, the Server Load balancer will distribute requests to other servers. The Server Load balancer will be able to retrieve Session data from the database because all Session data is stored in the database.

In short, we can use StateServer and SQL Server modes to deploy Web Farm. We need to avoid using InProc mode whenever possible.

Session and Cookie

The client uses cookies to use sessions. Because the client needs to provide a suitable Session ID for each request, we can use the following methods:

Use Cookie

ASP. NET uses a specific Cookie name: ASP. NET_SessionId, which is automatically provided when the Session set is created. This is the default setting and the Session ID is transmitted through cookies.

Cookie Munging

When a user sends a request to the server, the server decodes the Session ID and adds it to the link on each page. When the user clicks the link, ASP. NET encode the Session ID and send it to the page requested by the user. Now, the requested page can get the Session variable. All of this is done automatically when ASP. NET discovers that the user's browser does not support cookies.

How to Implement Cookie Munging

For this purpose, we must ensure that our Session State is Cookie-less.

Remove Session

The following method is used to remove a Session

Method Description
Session. Remove (strSessionName) Remove a project from Session State
Session. RemoveAll () Remove all items from the Session set
Session. Clear () Remove all items from the Session set. Note: Clear and RemoveAll. RemoveAll () are no different. Clear () is internal.
Session. Abandon () Cancels the current Session.

Enable and disable a Session

In terms of performance optimization, we can enable or disable the Session. Because the read/write Session on each page has some performance overhead, it is more suitable to enable or disable the Session, instead of using its default configuration: always. You can enable or disable a Session in either of the following ways:




We can disable Session in the EnableSessionState attribute of the page command.

Similarly, we can make it read-only, which will only allow access to the Session and prohibit writing information to the Session.


By setting the EnableSessionState attribute of web. config, the Session can be disabled throughout the application,

Generally, we use page-level restrictions to flexibly control the use of sessions.


How to Disable ASP. NET Session State


I hope you are more familiar with the Session, how to use the Session, and how to use it in the Web Farm. The following is a summary:

1. InProc Session Provider is the fastest, because all data is stored in the application memory, and Session data is lost when IIS is restarted or the site is recycled, you can use this mode on websites with a small number of users, but do not use it in Web Farm.

2. State Server mode: sessiondata is stored in the aspnet_state.exe application. It stores Session data outside the Web service. Therefore, problems in the Web service do not affect the Session data, before storing Session data to StateServer, We need to serialize the object. In Web Farm, we can safely use this mode.

3. SQL Server mode: This mode saves Session data to SQL Server. We need to provide connection strings and serialize objects during storage, this mode is very useful in the actual Web Farm production environment.

4. We can also use the custom mode. When we need to use an existing table to store Session data, we can also create custom Session IDs in the Custom mode, however, you are not recommended to implement the Provider by yourself. We recommend that you use a third-party Provider.

I hope you will like this article and hope that you can give me valuable suggestions to help you improve it together. Thank you again for reading this article.



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.