Summary of ASP. NET State Service and Session Lost Problem

Source: Internet
Author: User
Keywords asp net state server asp net state server service asp net session variables
Tags configuration settings server memory

When asp.net2.0 the system, there is a session loss problem when deleting or creating file operations in the program.

The following methods are used:
First, the implementation of the ASP:
The session is based on HttpModule technology, HttpModule can be processed in the request before the State control of the request, because the session itself is used to do state maintenance, so with the HttpModule to do the session is more appropriate.

Asp. How to maintain the status of session in net
Asp. NET provides a session object that allows programmers to identify, store, and process contextual information for several requests to a particular network application on the server by the same browser object. The session corresponds to the same conversation between the browser and the server, the server triggers the Session_OnStart event when the browser first requests a page of the Web application, and triggers the Session_OnEnd event when the conversation times out or is closed. Programmers can respond to these two events in code to handle tasks related to the same conversation, such as opening and releasing resources to be used for the conversation.

When you want to use the session object in an ASP. NET program, you must make sure that the EnableSessionState property in the page's @page instruction is true or readonly. And the sessionstate property is set correctly in the Web. config file.
Asp. The state of the session in net is determined by the Mode property of the <sessionstate> tag under the <system.web> tag in the Web. config file. There are four possible values for this property: Off, Inproc, StateServer, and SQL Server.

Set to OFF disables session.
InProc is the default setting, which is similar to the session state of the previous ASP, and the state of the session is stored in the ASP. NET process, and its advantages are obvious: performance. In-process data access will naturally be faster than the Kua process's access. However, the state of this session depends on the ASP. When the IIS process crashes or a normal restart occurs, the state saved in the process is lost.
In order to overcome the disadvantage of InProc mode, ASP. NET provides two ways to maintain session state outside of the process.
Asp. NET first provides a Windows service that provides: ASPState, after this service is started, ASP. NET application can set the Mode property to "Sateserver" to use the state management method provided by this Windows service.

In addition to setting the Mode property to StateServer in the Web. config file, you must also set the IP address and port number of the running StateServer server. If you run StateServer on the machine where IIS resides, the IP address is 127.0.0.1, The port number is usually 42424. The configuration is as follows:
Mode= "StateServer"
Stateconnectionstring= "tcpip=127.0.0.1:42424"
With this mode, session state storage will not depend on the failure or restart of the IIS process, and the state of the session will be stored in the memory space of the stateserver process.

Another session-state mode is SQL Server mode. This mode saves the state of the session in the SQL Server database. Before using this mode, you must have at least one SQL Server server and establish the required tables and stored procedures in the server. The. NET SDK provides two scripts to simplify this work: InstallSqlState.sql and UninstallSqlState.sql. These two files are stored in the following path:
<%systemdriver%>\winnt\microsoft.net\framework\<%version%>\
To configure a SQL Server server, you can run SQL Server-provided command-line tools on the command line Osql.exe
osql-s [Server name]-u [user]-p [Password] <installsqlstate.sql

For example:
Osql-s (local)-U as-p ""-I InstallSqlState.sql
After you have done the necessary database preparation, change the Mode property of the sessionstate element in the Web. config file to "SQL Server" and specify the SQL connection string. Specific as follows:
mode= "SQL Server"
sqlconnectionstring= "Data source=127.0.0.1;userid=sa;password=; Trusted_connection=yes "
Using SQL Server mode makes it possible for the session state to be independent of the IIS server, and it can also take advantage of the clustering of the servers so that the state store does not rely on a single SQL Server, which can provide great reliability for the application.


Second. Reasons for loss:
Turn (1): The reason and solution of unknown session in the default configuration of ASP.
During normal operation, the session will be lost for no reason. Because the program is constantly being manipulated, it is possible to exclude the session timeout. In addition, the session timeout is set to 60 minutes and will not expire so quickly.
Reasons and solutions to write them out.
Reason:
Because the ASP. NET program is the default configuration, the settings for the session in the Web. config file are as follows:
<sessionstate
Mode= ' InProc '
stateconnectionstring= ' tcpip=127.0.0.1:42424 '
sqlconnectionstring= ' data source=127.0.0.1; Trusted_connection=yes '
Cookieless= ' true '
Timeout= '/>

We will find that there is an attribute mode in the sessionstate tag, which can have 3 kinds of values: InProc, StateServer? SQL Server (case sensitive). By default it is InProc, which is to save the session in process (IIS5 is aspnet_ Wp.exe, while IIS6 is W3wp.exe), this process is unstable, and when certain events occur, the process restarts, causing the session stored in the process to be lost.
[The session of the ASP is process dependent.] The ASP session state is stored in the IIS process, which is the Inetinfo.exe program. So when the Inetinfo.exe process crashes, the information is lost. ]

Under what circumstances will the process be re-started? An article from Microsoft tells us:


  • memorylimit attribute of processmodel tag in configuration file

  • global.asax or Web. config file is changed

  •  The Web program (DLL) in the Bin folder has been modified

  • The antivirus software scanned some. config files.

For more information please refer to prb:session variables is lost intermittently in ASP.
Workaround:
In the sessionstate tag mentioned above, the mode attribute can have three values, in addition to the InProc, it can be stateserver, SQL Server. Both of these methods are out-of-process, so when the aspnet_wp.exe is re-started, it does not affect the session.

Now, please set mode to StateServer. StateServer is a service of this machine that can be seen in the system service with the service name of the ASP. NET State Service, which is not started by default. After we set mode to StateServer, please manually start the service. In this way, we can use the local stateservice to store the session, unless the computer restarts or Stateservice collapse, the session will not be lost (because the session timeout is discarded is normal).
In addition, we can also save the session through the stateservice of other computers [such as using the state server]. The specific changes are like this. Also in the sessionstate tag, there is a stateconnectionstring= ' tcpip=127.0.0.1:42424 ' attribute, which has an IP address, The default is native (127.0.0.1), you can change it to the computer IP that you know to run the Stateservice service, so that you can implement the ASP. NET program on different computers.

If you have higher requirements, you need to restart the service during the session is not lost, you can consider to set mode to SQL Server, you also need to modify the sqlConnectionString property. For an operation to save a session using SQL Server, please visit here.
When using StateServer or SQL Server to store a session, all objects that need to be saved to the session must be serialized in addition to the basic data type (the default data type, such as int, string, and so on). Just put the [Serializable] tag in front of the class you want to serialize.
Such as:
[Serializable]
public class MyClass
{
......
}
For specific serialization-related knowledge, please visit here.
At this point, the problem is resolved.

Reference article:
ASP. NET Session State FAQ
ASP. NET Session State
[ASP] Session explanation
Prb:session Data is Lost if you use ASP. InProc Session State Mode
Prb:session Data is Lost if you use ASP. InProc Session State Mode
ASP. NET HTTP Runtime
Serialization of objects in. NET



Note
(1) Using StateServer mode
Ensure that the server running the ASP is the remote server where you want to store session state information. The service is installed with ASP., and its default location is
< drive >:\systemroot\microsoft.net\framework\version\aspnet_state.exe.
In the application's Web. config file,
Set Mode=stateserver and set the stateConnectionString property.
For example, stateconnectionstring= "tcpip=sarath:42424".
(2) using SQL Server mode
Run InstallSqlState.sql on the computer that is running SQL Server (it will store session state)
(The default installation location is < drive >:\systemroot\microsoft.net\framework\version).
This creates a database named ASPState that has new stored procedures and has aspstatetempapplications tables and aspstatetempsessions tables in the TempDB database.
In the application's Web. config file, set mode=sqlserver and set the sqlConnectionString property. For example, sqlconnectionstring= "Data source=localhost;integrated security=sspi;initial catalog=northwind".
(3) Example
The following example specifies several session state configuration settings.

<configuration>
<system.web>
<sessionstate mode= "InProc"
Cookieless= "true"
Timeout= "/>"
</sessionState>
</system.web>
</configuration>
Requirements
Included in:<system.web>
WEB Platform: IIS 5.0, IIS 5.1, IIS 6.0
Configuration files: Machine.config, Web. config
Configuration section Handlers: System.Web.SessionState.SessionStateSectionHandler
Please see

ASP. NET Configuration | ASP. NET Settings Schema | SessionStateModule
[Reason:] in Windows2003 server IIS6 joined the application pool to reclaim some useless process function, when due to the site program error or too much traffic caused by the application pool will automatically reclaim the process, prevent the site into the "dead" state, This time the application pool recycling will cause the session variable is cleared, there is a phenomenon of the session variable is missing.
To solve this problem in Windows2003, we started the ASP. NET State Service on the server and made some changes in the system's Machine.config. Now by default the session state mode is StateServer. If your Web site root directory also has a Web. config profile, please change the mode= "InProc" to Mode= "StateServer", the following code, you can prevent the loss of the session variable:
<sessionstate
Mode= "StateServer"
Stateconnectionstring= "tcpip=127.0.0.1:42424"
sqlconnectionstring= "Data source=127.0.0.1;integrated Security=sspi"
Cookieless= "false"
timeout= "30"
/>
+ Note: Applies only to users that support ASP.


Turn (2): Reasons and some solutions
To save the session to the state server:
1. Start the Service "ASP. NET State Service",
2. Then, modify the Web. config:
<sessionstate
Mode= "StateServer"
Stateconnectionstring= "tcpip=127.0.0.1:42424"
sqlconnectionstring= "Data source=127.0.0.1; Trusted_connection=yes "
Cookieless= "false"
timeout= "140000"
/>
Note://mode= "StateServer" This mode is not lost even if the page is modified session!
Of course: mode= "InProc" If your pattern is this, you will lose the session when you modify the page!!!!!!

In Webconfig, the session will be set to SQL Server or StateServer, it will not lose the session,
The former needs to write to the database, which requires the system to open StateServer service.

Cause 1:
The files in the bin directory are overwritten, ASP. NET has a mechanism, in order to ensure that after the DLL is recompiled, the system will restart the Web site process, which will cause the session is lost, so if there is an Access database in the bin directory, or other files are overwritten by the system, it will cause the session to be lost. [The delete operation of the directory must lose the session.] The internal mechanism of ASP. Treats the directory a bit like a miser, it clings to the directory, you create it will not tube (to Riga), once created he will monitor the directory, if you want to delete or rename it (moving its directory), it will happen again. ]
Cause 2:
Folder Options, if you do not open the "Open folder window in a separate process", once you create a new window, the system may be considered a new session, and cannot access the original session, so you need to open this option, otherwise it will cause the session to be lost
Cause 3:
It seems that most of the session loss is caused by the client, so start with the client and see if the cookie is open
Cause 4:
Session time setting is not a problem, will not cause the loss due to timeouts.
[The default time is 20 minutes, you can set the session timeout in Web. config, such as 60 Minutes instead]
Cause 5:
Limits on the number of cookies in IE (20 cookies per domain) may cause session loss
Cause 6:
Using the Web garden mode and using the InProc mode as the way to save the session


Resolve Lost Experience
1. Determine if the cause is 1, and you can track the modification time of a file in the bin each time you refresh the page.
2. Do the session read and write log, each read and write session to record down, and to record SessionID, session value, where the page, the current function, the function of the first session of the operation, so that the reasons for missing will be more convenient
3. If allowed, it is recommended to save the session with State server or SQL Server, which is not easily lost
4. Add code in Global.asa to record session creation time and end time, the session loss caused by timeout can be recorded in Sessionend.
5. If you have some code that uses client-side scripting, such as JavaScript to maintain the session state, try debugging the script because the script error causes the session to be lost.


Turn (3): Session loss reason and solution summary
Possible cause 1:
The process is automatically reclaimed by the IIS6 default settings under Win2003 Server for each worker process running in the default application pool after more than 20 hours, causing the session saved in the process to be lost.

Because data such as Session,application is saved by default in the worker process that runs the Web application, it can be lost if the worker process is recycled.

Workaround:
Modify the configuration to automatically reclaim the worker process when it is set to automatic, such as set to automatically reclaim the process when it exceeds 60% of the existing physical memory. By using the default application pool, you can ensure that multiple applications are isolated from one another, ensuring that an application's crash does not affect the other Web application. You can also enable a standalone application to run under the privileges of a specified user account. This setting is not affected if the session is saved using the StateServer or SQL Server database method.

Possible cause 2:
The system is running in a load-balanced WEB farm environment, while the session state in the system configuration file Web. config is set to InProc (that is, the session state is stored locally), and the session is often timed out when the user accesses a large amount. The cause of this phenomenon is mainly because the user accesses the Web application through the load balanced IP, and at some point the session state is saved in a server, but the session state is not saved in the other Web front-end server, and as the concurrency increases, Load balancing is used as a route to access the idle server at any time, and the resulting idle server does not have a session state that was previously saved.

Workaround:
1. When you run an ASP. NET Web application in a load-balanced Web farm environment, be sure to use SQL Server or StateServer session state mode, where we do not select SQL Server mode to store session state based on performance considerations. Instead, select a sessionstateserver server to the user's session state. We want to set the following in the system configuration file Web. config:
<sessionstate
Mode= "StateServer" cookieless= "false" timeout= "240"
stateconnectionstring= "tcpip=192.168.0.1:42424" statenetworktimeout= "14400"/>
Also add an item
<machinekey
validationkey= "78ae3850338bfadce59d8ddf58c9e4518e7510149c46142d7aad7f1ad49d95d4" decryptionKey= " 5fc88dfc24ea123c "validation=" SHA1 "/>

2. We also launch the ASP. Sessionstateserver Server: Control Panel >> Administrative Tools >> Services >>asp.net State Service, set it to start automatically.

3. Microsoft Internet Information Services (IIS) settings for each front-end Web service
To maintain session state between different Web servers in a Web farm, the application path (for example, \lm\w3svc\2) of the Web site in the Microsoft Internet Information Services (IIS) configuration database must be the same as all Web servers in the Web farm. The case must also be the same, because the application path is case-sensitive. On a Web server, the instance ID of the Web site hosting the ASP. NET application might 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 path between Web servers in the Web farm is different. We must make the instance ID of the Web farm Web site the same. You can save one Web configuration information in IIS as a file, and the IIS configuration for other Web servers can come from this file. If you want to know the specific settings, visit the Microsoft Support Web site:


Turn (4): Missing issues Collection
SessionState's timeout), the main reasons are three kinds.
A: Some of the virus-killing software will scan your Web. config file, when the session is definitely off, this is Microsoft's argument.
Two: Inside the program has the code that lets the session lose, and the server memory is not enough to produce.
Three: The program has frame pages and cross-domain situations.
The first solution is to make the virus-killing software screen scan the Web. config file (don't edit it yourself while the program is running)
The second is to check whether the code has Session.Abandon () or something.
The third is to start the ASP. NET State Service in the window service.
Http://community.csdn.net/Expert/topic/3100/3100218.xml?temp=.4426386
There is also the possibility that you have changed the site's files during the test.

Here's what's in Help:
(Ms-help://ms. Vscc.2003/ms. msdnqtr.2003feb.2052/cpguide/html/cpconsessionstate.htm)
ASP. NET provides a simple, easy-to-use session-state model that you can use to store arbitrary data and objects across multiple WEB requests.
It does this by using a dictionary-based, in-memory object reference, which references the cache that exists in the IIS process.
Consider the following restrictions when using the in-process session state mode:
When using in-process session state mode, session state data is lost if the Aspnet_wp.exe or application domain restarts. These reboots typically occur in the following scenarios:
(1) in the <processModel> element of the application's Web. config file, set a property that causes the new process to start when the condition is met, such as memorylimit.
(2) Modify the Global.asax or Web. config file.
(3) Change to the \ Bin directory of the Web application.
(4) Scan and modify files in the \ Bin directory of the Global.asax file, Web. config file, or Web application with antivirus software.
(5) If Network Park mode is enabled in the <processModel> element of the application's Web. config file, do not use the in-process session state mode. Otherwise, random data loss will occur.

I've also met. The session or cookie on this machine is missing.
<sessionstate
Mode= "StateServer"
Stateconnectionstring= "tcpip=127.0.0.1:42424"
sqlconnectionstring= "Data source=127.0.0.1; Trusted_connection=yes "
Cookieless= "false"
Timeout= "40"
/>
Three properties of Mode= "". Local/other machine/sqlserver.
Many network architectures, between each server through a dedicated storage state of the server (dedicated state server) to save such as Session,cookie.

I have encountered this kind of problem before, I have used the following several methods to solve. No such situation is happening now.
1, release, do not debug release.
2, <sessionstate cookieless= "true" to set cookieless to true. Because the client disables cookies, the session is not valid.
3. Extend the session expiration time in IIS.
4, let antivirus software does not scan the Bin folder files and Web. config files.
I did it in a shady and dubious. But the session normal use! Oh ~ ~ I am lucky!

Nothing to say, do not use the session well, directly with the forms certification,
My system for the first two days was done with this, I feel very good.
Just encountered a similar problem: When using frameset, the session variable is missing.
Found a solution on Microsoft's website
http://support.microsoft.com/kb/323752/EN-US/
Don't know if it works?

IIS--->> application connection pooling--->> properties---->>[Recycle] [performance] [health] parameters as far as possible to the big change ^_^), I do not know the change to pull that is right, Anyway, after I have changed all the sessions are good to pull. The client's website and the backstage of the Dynamic Network Forum also follow the good pull.


Turn (5): Session of open new window in modal window is missing
have been depressed by this problem. A new modal window B is opened in window a using ShowModalDialog (). Then in the b window to do some business operations, and finally need to print some forms according to business operations, the result of the call to the open () method in B will appear the session lost phenomenon, prompting the user to re-login.
Two days have been chicken the same constant test of various methods. If you open the non-modal dialog in this window open method showModelessDialog () There is no problem, but the direct use of the open () method is not able to achieve the desired effect. Google on the Internet, to the major BBS to find answers, provide the simplest application. Finally found an article, which refers to the effective scope of the session object, but also did not specifically mention the problems I encountered:
In IE:
Valid window products include
1.Session objects are only valid in the window where the session object is created.
2. The window with the newly opened link in the window that created the session object has invalid Windows including
1. Start the IE browser window directly
2. The window that opens the link is not in the window that created the Session object. (That is, the author invokes the Open () method on the b window that pops up in the window that created the Session object.) )
Consider only in the window to establish the session object is valid, so in the child window re-use Session.setattribute () method, thought so can succeed, the result is still not, depressed.
Wake up in the morning to the inspiration, since the Sub-window caused the session is lost, in the parent window in any case there is still a variable of the session, I can not have to reset the session variable in the child window, but can directly call the parent window of the JavaScript function open () Method may be to the end.   No matter how you try it first, it turns out to be so. Many times the problem is this, want to lazy, so do not study, seek answers everywhere, finally still have to rely on their own to fix.


Reprint: Http://blog.csdn.net/High_Mount/archive/2007/05/09/1601854.aspx


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: info-contact@alibabacloud.com 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.