Session of ASP. NET Load Balancer

Source: Internet
Author: User
Tags session id sha1

In the Web farm, dynamic Web pages will often be due to a number of hosts to do the load and the loss of the session, there are a lot of information on the Internet, I will only experience the process I have to share with you:

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= "stateconnectionstring=" tcpip= 192.168.0.1:42424"statenetworktimeout=" 14400 "/>

Here the Red font IP must be a machine in the same domain, the second step on this machine, and its registry Hkey_local_machine\system\currentcontrolset\servi ces\aspnet_state\ Parameter
Change the S\allowremoteconnection key value to 1, and then restart the local ASP.

Also add an item
<machinekey validationkey= "78ae3850338bfadce59d8ddf58c9e4518e7510149c46142d7aad7f1ad49d95d4" decryptionKey= " 5fc88dfc24ea123c "validation=" SHA1 "/>

How do I generate MachineKey?

As the MSDN Standard says, "Configure the key so that it can be used to encrypt and decrypt Forms authentication Cookie data and view state data and use it to authenticate the out-of-process session state identity." "This means that many of the encryption in ASP is dependent on the value inside the MachineKey , such as the Forms authentication Cookie, ViewState encryption. By default, the ASP. NET configuration is generated on its own, if a single server is of course not a problem, but if multiple servers are load balanced,MachineKey also uses a dynamically generated way, MachineKey on each server Inconsistent values, resulting in encrypted results are inconsistent, cannot share authentication and viewstate, so for multiple server load balancing situation, be sure to configure the same MachineKeyat each site.

MachineKey generated algorithm:

ValidationKey = CreateKey (20);

DecryptionKey = CreateKey (24);

protected string CreateKey (int len)

{

byte[] bytes = new Byte[len];

New RNGCryptoServiceProvider (). GetBytes (bytes);

StringBuilder sb = new StringBuilder ();

for (int i = 0; i < bytes. Length; i++)

{

Sb. Append (String. Format ("{0:x2}", Bytes[i]);

}

Return SB. ToString ();

}

Matchinekey Configuration With reference:

<?xml version= "1.0"?>

<configuration>

<system.web>

<MachineKey validationkey= "3ff1e929bc0534950b0920a7b59fa698bd02dfe8" decryptionkey= " 280450bb36319b474c996b506a95aedf9b51211b1d2b7a77 "decryption=" 3DES "validation=" SHA1 "/>

</system.web>

</configuration>

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 website: http://support.microsoft.com/default.aspx?scid=kb;zh-cn;325056

To supplement some relevant information:
Prb:session Variables is Lost If you use FRAMESET in Internet Explorer 6.0
http://support.microsoft.com/kb/323752/EN-US/#

Prb:session Data is Lost if you use ASP. InProc Session State Mode
http://support.microsoft.com/?id=324772

PRB: Session state is lost if you use SQL Server or StateServer session mode in a Web farm
http://support.microsoft.com/default.aspx?scid=kb;zh-cn;325056

ASP. NET Session State FAQ
Http://www.eggheadcafe.com/articles/20021016.asp

Reference from: Http://hi.baidu.com/panshuaiyang

How the application stores session information in two ways

The following actions are mainly for this section of the configuration deployment. Let's take a look at the meaning of the content contained in this section of the configuration. The syntax for the sessionstate node is this:

<sessionstate mode= "off| inproc| stateserver| SQL Server "
Cookieless= "True|false"
timeout= "Number of minutes"
Stateconnectionstring= "Tcpip=server:port"
sqlconnectionstring= "SQL connection string"
statenetworktimeout= "Number of seconds"
/>


Required properties are

Property Options Description
Mode settings where to store the session information
OFF is set to do not use the session function
The InProc is set to store the session inside the process, which is the default value for storage in ASP.
The StateServer is set to store the session in a separate state service.
SQL Server settings stores the session in a

The optional properties are:

Property Options Description
Cookieless set where the client's session information is stored
Ture using cookieless mode
False use cookie mode, which is the default value.
Timeout sets the number of minutes after which the server automatically discards session information. Default is 20 minutes
stateConnectionString sets the server name and port number used when the session information is stored in the State service, for example: "tcpip=127.0.0.1:42424". When the value of mode is StateServer Yes, this property is required.
sqlConnectionString sets the connection string when connecting to SQL Server. For example, "Data source=localhost;integrated security=sspi;initial catalog=northwind". This property is required when the value of mode is SQL Server.
stateNetworkTimeout settings when the session state is stored using StateServer mode, the TCP/IP connection to the server that stores the state information is disconnected after the number of seconds that the Web server is idle. The default value is 10 seconds.
Asp. The storage of client session state in net
In the introduction of the session model above, we can find that the session state should be stored in two places, namely the client and server side. The client is only responsible for saving the SessionID of the corresponding website, while the other session information is saved on the server side. In ASP, the SessionID of the client is actually stored in the form of a cookie. If a user chooses to disable cookies in the browser's settings, he or she will not be able to enjoy the convenience of the session or even have access to certain websites. In order to solve the above problems, the client's session information is stored in asp: Two kinds of cookies and cookieless.

Asp. NET, by default, the session information is stored on the client or using a cookie. If we want to store session information as a client using cookieless, here's how:

Locate the root directory of the current Web application, open the Web. config file, and locate the following paragraph:

<sessionstate
Mode= "InProc"
Stateconnectionstring= "tcpip=127.0.0.1:42424"
sqlconnectionstring= "Data source=127.0.0.1; Trusted_connection=yes "
Cookieless= "false"
Timeout= "20"
/>

The cookieless= "false" in this paragraph is replaced by the following: Cookieless= "true", so that the client session information is no longer stored using a cookie, but rather it is stored through a URL. Close the current IE, open a new IE, revisit the Web application, and you will see something like this:


In http://localhost/MyTestApplication/(ulqsek45heu3ic2a5zgdl245)/default.aspx, the client's session ID is marked in bold. Note that this information is automatically added by IIS and does not affect the previous normal connection.

Asp. The storage of server-side session state in net
Preparatory work

For you to experience the experiment better, you can create a page called sessionstate.aspx, and then 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!"
Else
Span1. InnerHtml = "Your session contains: <font color=red>" & \
Session ("MySession"). ToString () & "</font>"
End If
End Sub
</script>
<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" >
</form>
<fontsize= "6" ><spanid= "Span1" runat= "Server"/></font>

This sessionstate.aspx page can be used to test if the session information is missing on the current server.

Storing server session information in a process
Let's go back to the paragraph in the Web. config file just now:

<sessionstate
Mode= "InProc"
Stateconnectionstring= "tcpip=127.0.0.1:42424"
sqlconnectionstring= "Data source=127.0.0.1; Trusted_connection=yes "
Cookieless= "false"
Timeout= "20"
/>
When the value of mode is InProc, it indicates that the server is using this mode.

This approach is the same as in the previous ASP, where the server stores session information in the IIS process. When IIS shuts down and restarts, this information is lost. But this model also has its own greatest benefit, is the highest performance. All session information should be stored in the IIS process, so IIS can quickly access this information, which is much faster than storing session information out of process or storing session information in SQL Server. This mode is also the default for ASP.

Okay, now let's do an experiment. Open the Sessionstate.aspx page and enter some characters to store it in the session. Then, let's let IIS restart. Note that instead of stopping the current site from starting, you can choose to restart IIS by right-clicking on the node of the native machine name in IIS. (If you want to use NT4, restart IIS must restart the computer before the line, Microsoft really @#$%^&) back to the Sessionstate.aspx page, check the session information just now, found that the information has been lost.

Store server session information outside the process
First, let's open the management tools, service, and find a service named: ASP. NET State service to start it. In fact, the service is to start a process to save the session information. After starting this service, you can see a process called Aspnet_state.exe from the Windows Task Manager, which is the process in which we save the session information.

Then, go back to the above paragraph in the Web. config file and change the value of mode to StateServer. After saving the file, reopen an IE, open the sessionstate.aspx page and save some information to the session. At this point, let us restart IIS, and then go back to the Sessionstate.aspx page to view the session information just now, found not lost.

In fact, the way the session information is stored out-of-process refers not only to the process of storing information in the local computer, but also to the process of storing the session information in other servers. In this case, you need not only change the value of mode to StateServer, but also configure the corresponding parameters in the stateconnectionstring. For example, your calculation is 192.168.0.1, and you want to store the session in the process of the IP-192.168.0.2 computer, you need to set it up like this: stateconnectionstring= "tcpip= 192.168.0.2:42424 ". Of course, don't forget to load the. NET Framework in the 192.168.0.2 computer and start the ASP.

Store the server session information in SQL Server
First of all, let's do some preparatory work. Start SQL Server and the SQL Server Agent service. Execute a script file called InstallSqlState.sql in SQL Server. This script file will create a database in SQL Server dedicated to storing session information, and a SQL Server Agent job that maintains the session information database. We can find the file in the following path:

[System drive]\winnt\microsoft.net\framework\[version]\
Then open Query Analyzer, connect to the SQL Server server, open the file you just made and execute. Wait a moment, the database and the job is set up. At this point, you can open Enterprise Manager and see a new database called ASPState. But this database is just a few stored procedures, no user tables. The session information is actually stored in the ASPStateTempSessions table in the tempdb database, and the other Aspstatetempapplications table stores the Application object information in the ASP. These two tables were also created by the script just now. In addition to view Management->sql Server Agent----jobs, found also a job called aspstate_job_deleteexpiredsessions, this job is actually Go to the ASPStateTempSessions table every minute to delete the expired session information.

Next, we go back to the Web. config file and change the value of mode to SQL Server. Note that you also want to modify the value of the sqlconnectionstring at the same time, in the format:

sqlconnectionstring= "Data source=localhost; Integrated Security=sspi; "
Where data source refers to the IP address of the SQL Server server, if SQL Server and IIS are a machine, write 127.0.0.1. Integrated SECURITY=SSPI means that Windows Integrated authentication is used, so that access to the database is made as an ASP, and by this configuration, SQL can be obtained that is more than using the userid=sa;password= password Better security for server authentication. Of course, if SQL Server is running on another computer, you may need to maintain the consistency of validation on both sides of the way through Active Directory domains.

Again, let's do an experiment. Add session information to the sessionstate.aspx, then found that the session information already exists in SQL Server, even if you restart the computer, just the session information will not be lost. Now, you've seen exactly what the session message looks like, and it's stored in SQL Server.

Session of ASP. NET Load Balancer

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.