Detailed explanation of ASP. NET sessions and causes of inexplicable session loss and Solutions

Source: Internet
Author: User
Tags object serialization


Session model Overview

What is session? Simply put, it is the number that the server sends to the client. When a WWW server is running, several users may browse the website running on this server. When a user establishes a connection with the WWW server for the first time, the user establishes a session with the server, and the server automatically assigns a sessionid to the user to identify the unique identity. This sessionid is a random string consisting of 24 characters on the WWW server. We will see it in the following experiment.

This unique sessionid has great practical significance. When a user submits a form, the browser automatically attaches the user's sessionid to the HTTP header information (this is an automatic function of the browser and the user will not notice it ), after the server processes the form, it returns the result to the user corresponding to the sessionid. Imagine how the server knows which user submitted the form when two users register simultaneously without sessionid. Of course, sessionid has many other functions, which we will mention later.

In addition to sessionid, each session contains many other information. However, for ASP or ASP. NET Programming and programming, the most useful thing is to access ASP/ASP. NET's built-in Session object to store their own information for each user. For example, if we want to know how many pages a user visits our website browses, we may add the following to each page that a user may access:


If SESSION ("pageviewed") = "" then

Session ("pageviewed") = 1


Session ("pageviewed") = SESSION ("pageviewed") + 1

End if


You can use the following sentence to learn about several pages you have browsed:


Response. Write ("You have viewed" & SESSION ("pageviewed") & "pages ")


Some readers may ask: where does this seemingly array SESSION ("...") come from? Do I need to define it? In fact, this session object is a built-in object of the WWW server with ASP interpretation capability. That is to say, this object has been defined for you in the ASP system, and you only need to use it. The variable name in session ("...") is like the variable name. In session ("...") = $, $ is the variable value. You only need to write a sentence to access the value in the variable .. on every page of the user.

In fact, Asp has a total of seven built-in objects, including session, application, Cookie, response, request, server, etc. Similar objects are also available in other server-side scripting languages such as JSP and PHP, but they are not the same in terms of naming or usage.

ASP session functional defects

Currently, ASP developers are using session, but they have discovered the following defects in ASP session:

Process dependency: the ASP sessionstate is stored in the iisprogress, And the inetinfo.exe program is also used. When the inetinfo.exe process crashes, the information is lost. In addition, restarting or disabling the IIS service will cause information loss.

Limitations of the range of session Status usage: when a user accesses another website from one website, the session information will not be migrated. For example, there may be more than one WWW server on the Sina website. After a user logs on, he/she will go to various channels, but each channel is on a different server, what if I want to share session information on these www servers?

Cookie dependency: in fact, the client's session information is stored in the cookie. If the client completely disables the cookie function, it cannot enjoy the function provided by the session.

In view of the above defects of ASP session, Microsoft designers are designing and developing ASP. net session, and the above defects are completely overcome, making ASP. net session has become a more powerful feature.

Introduction to the Web. config file

Some ASP. NET programmers say: What is the Web. config file? I have never heard of it, but can the program I wrote work properly? Yes, you are right. Without the Web. config file program, it can run normally. However, if you create a large website, you need to make some overall configuration for the entire website, for example, you need to use the web. config file. Although some options in the web. config file can be configured through IIS, if the corresponding settings in Web. config also overwrite the configuration in IIS. In addition, the biggest convenience of the web. config file is that you can access the settings in Web. config by calling the system. Web namespace on the ASP. NET page.

There are two types of Web. config: the server configuration file and the web application configuration file, both named Web. config. This configuration file stores a series of information about the web pages written in which language, Application Security Authentication mode, and session information storage mode on the current IIS server. This information is saved using XML syntax. If you want to edit it, use the text editor.

The server configuration file takes effect for all applications on all sites on the IIS server. In. NET Framework 1.0, the Web. config file of the server exists in \ winnt \ Microsoft. NET \ framework \ v1.0.3705.

The Web application configuration file web. config is stored in various web applications. For example, the root directory \ Inetpub \ wwwroot of the current website, and the current web application is myapplication, the root directory of the Web application should be \ Inetpub \ wwwroot \ myapplication. If your website has only one web application, the root directory of the application is \ Inetpub \ wwwroot. To add a web application, add a virtual directory with the application starting point in IIS. The files and directories under this directory are considered as a web application. However, adding a web application through IIS does not generate a web. config file for you. To create a web application with a web. config file, you must use visual
Studio. NET to create a web application project.

The Web. config configuration file of the Web application is optional and optional. If not, each web application uses the Web. config configuration file of the server. If yes, the corresponding values in the web. config configuration file of the server will be overwritten.

In ASP. NET, modifications to Web. config will automatically take effect immediately after they are saved. You do not need to restart the web application to take effect after modifying the configuration file in ASP.

Session configuration information in the web. config file

After opening the configuration file web. config of an application, we will find the following section:


Mode = "inproc"

Stateconnectionstring = "TCPIP = 42424"

Sqlconnectionstring = "Data Source =; trusted_connection = yes"

Cookieless = "false"

Timeout = "20"


This section describes how the application stores session information. The following operations mainly aim at this configuration section. Let's take a look at the meaning of the content contained in this section. The syntax of the sessionstate node is as follows:

<Sessionstate mode = "off | inproc | StateServer | sqlserver"

Cookieless = "True | false"

Timeout = "number of minutes"

Stateconnectionstring = "TCPIP = server: Port"

Sqlconnectionstring = "SQL connection string"

Statenetworktimeout = "number of seconds"


The required attribute is

Attribute option description

Mode setting: Where to store session information

Off is set to not use the session Function

Inproc is set to store sessions in the process, which is the storage method in ASP. This is the default value.

StateServer is set to store sessions in independent State services.

Sqlserver settings store sessions in SQL Server.

Optional attributes:

Attribute option description

Cookieless sets where the session information of the client is stored

Ture uses cookieless Mode

False uses cookie mode, which is the default value.

Timeout specifies the number of minutes after which the server automatically waives the session information. The default value is 20 minutes.

Stateconnectionstring is the name and port number of the server used to store session information in the status service, for example, "TCPIP = 42424 ". This attribute is required when the mode value is StateServer.

Sqlconnectionstring sets the connection string when connecting to SQL Server. For example, "Data Source = localhost; Integrated Security = sspi; initial catalog = northwind ". This attribute is required when the mode value is sqlserver.

Statenetworktimeout sets the number of seconds after the session state is stored in StateServer mode and the TCP/IP connection between the Web server and the server that stores the status information. The default value is 10 seconds.

Storage of client session Status in ASP. NET

In our previous session model introduction, we can find that the session status should be stored in two places: client and server. The client is only responsible for saving the sessionid of the corresponding website, while other session information is stored on the server. In ASP, the sessionid of the client is actually stored as a cookie. If the user chooses to disable cookies in the browser settings, then he will not be able to enjoy the convenience of the session, or even access some websites. To solve the above problems, the session information storage methods of the client in ASP. NET are divided into cookie and cookieless.

In ASP. NET, by default, session information is stored on the client using cookies. If you want to use cookieless on the client to store session information, the method is as follows:

Find the root directory of the current web application, open the Web. config file, and find the following section:


Mode = "inproc"

Stateconnectionstring = "TCPIP = 42424"

Sqlconnectionstring = "Data Source =; trusted_connection = yes"

Cookieless = "false"

Timeout = "20"


In this section, cookieless = "false" is changed to cookieless = "true". In this way, the session information of the client is no longer stored using cookies, but stored through URLs. Close the current IE, open a new IE, and re-access the Web application, you will see something similar to the following:

Http: // localhost/mytestapplication/(ulqsek45heu3ic2a5zgdl245)/default. aspx indicates the session ID of the client. Note that this information is automatically added by IIS and does not affect the normal connection.

Storage of server session Status in ASP. NET


To better experience the experiment, you can create a page named sessionstate. aspx and add the following code to <body> </body>.

<Scriptrunat = "server">

Sub session_add (sender as object, e as eventargs)

Session ("mysession") = text1.value

Span1.innerhtml = "session data updated! <P> your session contains: <font color = Red> "&\

Session ("mysession"). tostring () & "</font>"

End sub

Sub checksession (sender as object, EAS eventargs)

If (Session ("mysession") is nothing) then

Span1.innerhtml = "nothing, session data lost! "


Span1.innerhtml = "your session contains: <font color = Red> "&\

Session ("mysession"). tostring () & "</font>"

End if

End sub


<Formrunat = "server" id = "form2">

<Inputid = "text1" type = "text" runat = "server" name = "text1">

<Inputtype = "Submit" runat = "server" onserverclick = "session_add"

Value = "add to session state" id = "submit1" name = "submit1">

<Inputtype = "Submit" runat = "server" onserverclick = "checksession"

Value = "View session state" id = "submit2" name = "submit2">


<Hrsize = "1">

<Fontsize = "6"> <spanid = "span1" runat = "server"/> </font>

This sessionstate. ASPX page can be used to test whether session information is lost on the current server.

Store Server session information in the process

Let's go back to the section in the web. config file:


Mode = "inproc"

Stateconnectionstring = "TCPIP = 42424"

Sqlconnectionstring = "Data Source =; trusted_connection = yes"

Cookieless = "false"

Timeout = "20"


When the mode value is inproc, it indicates that the server is using this mode.

This method is the same as the previous ASP mode, that is, the server stores session information in the IIS process. When IIS is disabled or restarted, the information is lost. However, this mode also has its own biggest advantage, that is, the highest performance. It should be that all session information is stored in the IIS process, so IIS can quickly access this information, the performance of this mode is much faster than that of session information stored outside the process or stored in SQL Server. This mode is also the default mode for ASP. NET.

Now let's do a test. Open the sessionstate. ASPX page and enter some characters to store them in the session. Then, let's restart IIS. Note that it is not to stop the current site and start again, but to right-click the node of the machine name in IIS and choose restart IIS. (To restart IIS when NT4 is used, you must restart the computer. Microsoft returns sessionstate. on the ASPX page, check the session information and find that the information has been lost.

Store Server session information outside the process

First, let's open the management tool> service, find the service named ASP. NET State service, and start it. In fact, this service is to start a process to save session information. After starting this service, you can see a process named aspnet_state.exe in the Windows Task Manager> process. This is the process for saving session information.

Return to the preceding section in the web. config file and change the mode Value to StateServer. Open another IE after saving the file, open the sessionstate. ASPX page, and save some information to the session. At this time, let's restart IIS and return to the sessionstate. ASPX page to view the session information.

In fact, this method of storing session information outside the process not only means that the information can be stored in the local process, but also the session information can be stored in other server processes. In this case, you not only need to change the mode Value to StateServer, but also need to configure the corresponding parameters in stateconnectionstring. For example, if you want to store the session in the process of a computer whose IP address is, you need to set it to stateconnectionstring = "TCPIP = 42424 ". Of course, do not forget to install. net on the computer
And start the ASP. NET State Services Service.

Store Server session information in SQL Server

First, let's make some preparations. Start the SQL Server and SQL Server proxy services. Execute a script file named installsqlstate. SQL in SQL Server. This script file will create a database in SQL Server for storing session information and an SQL Server proxy job for maintaining the session information database. You can find the file in the following path:

[System Drive] \ winnt \ Microsoft. NET \ framework \ [version] \

Then open the query analyzer, connect to the SQL Server server, open the file and execute it. Wait a moment and the database and job will be created. In this case, you can open the Enterprise Manager and see a new database called aspstate. However, this database only contains some stored procedures and does not use user tables. In fact, session information is stored in the aspstatetempsessions table of the tempdb database, and the other aspstatetempapplications table stores the Application Object Information in ASP. These two tables are also created by the script just now. In addition, you can view "manage"> "SQL Server proxy"> "job" and find another job called aspstate_job_deleteexpiredsessions. This job actually deletes expired session information from the aspstatetempsessions table every minute.

Then, we return to the Web. config file and change the mode Value to sqlserver. Note: You must also modify the sqlconnectionstring value in the following format:

Sqlconnectionstring = "Data Source = localhost; Integrated Security = sspi ;"

Data source refers to the IP address of the SQL Server server. If SQL Server and IIS are a server, write Integrated Security = sspi means to use Windows Integrated Identity Authentication, so that accessing the database will use ASP.. Net identity, through this configuration, you can obtain better security than the SQL Server authentication method using userid = sa; Password = password. Of course, if SQL server runs on another computer, you may need to maintain consistency between the two sides through Active Directory domains.

Similarly, let's do a test. Add the session information to sessionstate. aspx and you will find that the session information already exists in SQL Server. Even if you restart the computer, the session information will not be lost. Now, you have fully seen what session information looks like and what it is stored in SQL Server. What you can do depends on your performance.


Through this article, you can see that in terms of session management and maintenance, ASP. NET has made great progress over ASP. We can select a suitable method at will. For enterprise applications, this is undoubtedly beneficial to server synchronization, server stability, and reliability. I believe that with the support of powerful Microsoft, the new generation of e-commerce platforms will be built better!

Appendix: causes and solutions for inexplicable session loss under's default configuration

Because the program is configured by default, the session settings in the web. config file are as follows:
<Sessionstate mode = 'inc' stateconnectionstring = 'tcpip = 42424 'sqlconnectionstring = 'data source =; trusted_connection = Yes 'cookieless = 'true' timeout = '60'/>

The sessionstate label has an attribute mode, which can be inproc, StateServer, or sqlserver (case sensitive ). The process is unstable. When some events occur, the process restarts, causing the loss of sessions stored in the process.

Under what circumstances will the process be restarted? An article by Microsoft tells us:
1. memorylimit attribute of the processmodel label in the configuration file
2. The Global. asax or web. config file is changed.
3. The web program (DLL) in the bin folder is modified.
4. Anti-Virus Software scanned some. config files.
For more information, see PRB: Session variables are lost intermittently in ASP. NET applications.


In the sessionstate label mentioned above, the mode attribute can have three values: StateServer and sqlserver. The two session types are both external, so when aspnet_wp.exe is restarted, the session will not be affected.

Set the mode to StateServer. StateServer is a service on the local machine. You can see the service named ASP. Net state service in the system service. It is not started by default. After we set the mode to StateServer, manually start the service.

In this way, we can use the stateservice of the Local Machine to store sessions. The session will not be lost unless the computer restarts or the stateservice breaks down (it is normal that the session is discarded due to session timeout ).

In addition, sessions can be saved through stateservice on other computers. The specific modification is as follows. Also in the sessionstate label, there is a stateconnectionstring = 'tcpip = 8080' attribute, where there is an IP address, the default is the local machine ( ), you can change it to the IP address of the computer that runs the stateservice service as you know, so that the program located on different computers can communicate with each other.

If you have higher requirements and the session is not lost when the service period is restarted, you can set the mode to sqlserver and modify the sqlconnectionstring attribute. For information on how to use sqlserver to save sessions, visit here.

When you use StateServer or sqlserver to store a session, all objects to be saved to the session must be serialized except the basic data type (default data type, such as int and string. You only need to put the [serializable] label before the class to be serialized.
For example:
Public class myclass
For more information about serialization, see here.

Now, the problem is solved.

ASP. NET session state FAQ
ASP. NET session state
[ASP. NET] session details
PRB: session data is lost when you use ASP. NET inproc session state Mode
PRB: session data is lost when you use ASP. NET inproc session state Mode
ASP. net http Runtime
Object serialization in. net



Possible cause 1:

IIS6 under win2003 server is set by default. After more than 20 hours, every worker process running in the default application pool is automatically reclaimed, resulting in the loss of session stored in the process.

Because session, application, and other data are stored in the worker process that runs the web application by default, if the worker process is recycled, it will cause loss.


Modify the configuration and set it to automatically recycle the worker process from time to time. For example, set it to automatically recycle the worker process when it exceeds 60% of the occupied physical memory.

This process. By using the default application pool, you can ensure that multiple applications are isolated from each other, so that the crash of one application will not affect other web applications. It also allows an Independent Application to run under a specified user account privilege. If you use StateServer or SQL Server database to save the session, this setting is not affected.

Possible cause 2:

The system must run in a load balancing web environment, and the system configuration file web. the session Status in config is set to inproc (that is, the session status is stored locally), which leads to the situation where the session often times out when the user's access volume is large. This is mainly because the user accesses the web application system through the load balancing IP address, and saves the session Status of a session on a server at a certain time, however, the session Status of the session is not saved on other Web Front-end servers. As the concurrency increases, the load balancing function can be used as a route to access idle servers at any time, as a result, the idle server does not have the previously saved session status.

1. when you run ASP. net web applications must use sqlserver or StateServer session Status mode. In the project, we did not select sqlserver mode to store session status based on performance considerations, instead, select a sessionstateserver server to view the session Status of the user. We need to set the following in the System Configuration File web. config:
<Sessionstate mode = "StateServer" cookieless = "false" timeout = "240" stateconnectionstring = "TCPIP = 42424" statenetworktimeout = "14400"/>

Add another item
<Machinekey validationkey = "Hangzhou" decryptionkey = "5fc88dfc24ea123c" validation = "sha1"/>

2. we also need to start ASP on the sessionstateserver server. net State service, specific settings: Control Panel> Management Tools> services> Asp. net State service, set it to automatic start.

3. Microsoft "Internet Information Service" (IIS) settings for each front-end Web Service
To maintain the session status between different Web servers in the Web farm, Microsoft "Internet Information Service" (IIS) configures the Application Path of the web site in the database (for example, \ lm \ W3SVC \ 2) must be the same as all Web servers in the Web field. The application path must be case sensitive. On a Web server, the instance id of the Web site that hosts ASP. NET Applications may be 2 (where the application path is \ lm \ W3SVC \ 2 ). On another Web server, the instance id of the web site may be 3 (where the application path is
\ Lm \ W3SVC \ 3 ). Therefore, the application paths between Web servers in the Web field are different. We must make the instance IDs of the Web site the same. You can save a web configuration as a file in IIS. the IIS configuration of other web servers can come from this file. If you want to know the specific settings, visit the Microsoft support website:

Additional information:
PRB: Session variables are lost if you use frameset in Internet Explorer 6.0
Http:// /#

PRB: session data is lost when you use ASP. NET inproc session state Mode
Http:// /? Id = 324772

PRB: If you use sqlserver or StateServer session mode, the Web field will lose the session status.
Http:// SCID = KB; ZH-CN; 325056

ASP. NET session state FAQ

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.