In-depth analysis of Session Server Configuration Guide and user experience

Source: Internet
Author: User
This article provides a detailed analysis of the Session Server Configuration Guide and user experience. For more information, see I. Summary
All Web programs use Session to save data. the Independent Session server can solve the Session sharing problem in the server load balancer scenario. this article introduces. NET platform, and introduces various experiences and skills in using Session.

II. Session, SessionID, and Cookies
Session data is stored on the server, but each client needs to save a SessionID, which is stored in Cookies and expires when the browser is closed.

The HTTP request sent to the server contains the SessionID. the server obtains the Session information of this user based on the SessionID.
Many junior developers do not know the relationship between SessionID and Cookies. this is incorrect. it is because SessionID is stored in Cookies that, when we save Cookies, be sure not to cause the SessionID object because of the size and number of Cookies. in our program, Cookies of SessionID are specially processed:

The code is as follows:


///


/// Write cookie.
///
///
///
Public bool SetCookie (int day)
{
String CookieName = GetType (). ToString ();
HttpCookie SessionCookie = null;
// Backup SessionId.
If (HttpContext. Current. Request. Cookies ["ASP. NET_SessionId"]! = Null)
{
String SesssionId = HttpContext. Current. Request. Cookies ["ASP. NET_SessionId"]. Value. ToString ();
SessionCookie = new HttpCookie ("ASP. NET_SessionId ");
SessionCookie. Value = SesssionId;
} // Omit the middle part of the code. only the logic for backing up the SessionID and retrieving the SessionID is retained.
// If the total number of cookies exceeds 20, rewrite ASP. NET_SessionId to prevent Session loss.
If (HttpContext. Current. Request. Cookies. Count> 20 & SessionCookie! = Null)
{
If (SessionCookie. Value! = String. Empty)
{
HttpContext. Current. Response. Cookies. Remove ("ASP. NET_SessionId ");
HttpContext. Current. Response. Cookies. Add (SessionCookie );
}
}
Return true;
}


III. several methods for setting up a Session server
By saving sessions on an independent server, you can share sessions among multiple Web servers. although we can also develop the Session storage system by ourselves, we can use ASP. NET built-in storage mechanism will be more convenient.
. NET provides five ways to save the Seission:

Method name

Storage method Performance

Off

Set to not use the Session function

None

InProc

Set the Session to be stored in the process, that is, the ASP storage method. this is the default value.

Highest Performance

StateServer

Set to store sessions in independent state services. Usually the aspnet_state.exe process.

Performance loss: 10-15%

SQLServer

Set to store sessions in SQL Server.

Performance loss: 10-20%

Customer

Custom storage solution

Determined by the implementation method

We can. the Session storage method used by the configuration program in Config. by default, InProc is saved in the IIS process. this article does not explain Off, InProc, and Customer. you can search related articles online.
The following describes the applications of StateServer and SQLServer.

4. set up a Session server in StateServer mode
(1) server configuration
1. start the Asp.net State service. (the default status of this service is manual. change it to automatic and start .)
2. modify the registry: [HKEY_LOCAL_MACHINE \ SYSTEM \ ControlSet001 \ Services \ aspnet_state \ Parameters]
Set AllowRemoteConnection = 1 and Port = 42424 (decimal, 42424 by default)
Port is the service Port number.
AllowRemoteConnection indicates whether to allow connections from other machines. 0 indicates that the connection can only be used by the local machine, and 1 indicates that the connection can be used by other machines.

(2) client settings
In the Web. Config of the Web application, we need to modify / Of Node. If no
If not, add (the InProc method is used by default)

The code is as follows:


Mode = "StateServer"
StateConnectionString = "tcpip = server ip address: 42424"
Cookieless = "false"
Timeout = "60"/>


The above parameters can be modified as needed.

5. set up a Session server in SqlServer mode
(1) server configuration
There are two ways to set up the Session server using SqlServer mode. for ASP. NET 1.0 and 1.1, use a and 2.0, that is, use B.

A. create a Session database using an SQL file
In ASP. NET 1.0 and 1.1, you can only use this formula. for example, use the aspnet_regsql.exe tool. (of course, this method is also applicable to version 2.0)
. Net provides the database installation script, which can be found in the windows folder of the machine:
C: \ WINDOWS \ Microsoft. NET \ Framework \ v2.0.50727 \ InstallSqlState. SQL
C: \ WINDOWS \ Microsoft. NET \ Framework \ v2.0.50727 \ InstallSqlStateTemplate. SQL
Depending on the version of ASP. NET, you need to use different SQL scripts. ASP. NET mainly has two versions: 1.1 and 2.0. you can find these two SQL statements in different version folders.
InstallSqlState. SQL is the database with the default name "[ASPState]". This SQL can be run directly.
InstallSqlStateTemplate. SQL can save data using the database you specified. This SQL needs to be modified and run. open the SQL file and replace [DatabaseNamePlaceHolder] with the database name you specified.
You do not need to specify a database when executing installsqlstate. SQL, which can be executed on any database. This SQL statement creates a new database by yourself.

B. use the aspnet_regsql.exe tool.
After ASP. NET 2.0133, the aspnet_regsql.exe tool is soft enough to easily configure the Session database. This tool is located in the "system root directory Microsoft. NET \ Framework \ version" folder on the Web server.
Example:
Aspnet_regsql.exe-S.-U sa-P 123456-ssadd-sstype p
-S parameters:
Indicates the database instance name. you can use "." to indicate the local machine.
-U and-P parameters:
Indicates the user name and password.
-E parameter:
You can select a group in-U-P and-E.-E indicates that the current system user logs on to the database through windows Authentication, and-U-P indicates that the SQL Server user logs on to the database.
-Ssadd/-ssremove parameters:
-Ssadd indicates that the Session database is added, and-ssremove indicates that the Session database is removed.
Sstype parameters:

Option

Description

T

Store session data in the SQL Server tempdb database. This is the default setting. If session data is stored in the tempdb database, session data is lost when SQL Server is restarted.

P

Store session data in the ASPState database instead of the tempdb database.

C

Store session data in a custom database. If you specifyCOption, you must also use-DThe options include the name of the custom database.

(2) Session client settings
This room also requires the Web application to modify Node. if the default database (ASPState Library) is used, the configuration is as follows:

The code is as follows:


Mode = "SQLServer"
SqlConnectionString = "server = 192.168.9.151; uid = sa; pwd = 123456 ;"
/>


If a custom database name is used, you also need to set the allowCustomSqlDatabase attribute and specify the database in the database connection string:

The code is as follows:


Mode = "SQLServer"
AllowCustomSqlDatabase = "true"
SqlConnectionString = "server = 192.168.9.151; DataBase = MyAspState; uid = sa; pwd = 123456 ;"
/>


6. summary of experience and skills
The following is a summary of the experience and skills of SessionID, Session_End time, StatServer mode, and SqlServer mode.
(1) StateServer mode:
1. in web farm, make sure that the same
2. objects to be stored in the Session can be serialized.
3. to maintain the session state on different web servers in the web farm, the path of the website application in IIS Metabase (for example, \ LM \ W3SVC \ 2) it should be consistent (case sensitive) on all servers ).
4. ASP. NET processes the Session in the Machine. the HttpModuel module configured in Config, in. in the Config folder under the installation directory of. NET, view the Web. config (version 1.1 is in Machine. config ):

The code is as follows:



...
...


Check whether this module exists.
5. StateServer does not support server load balancer. Therefore, if the SQL Server mode is recommended for large concurrency, you can enjoy the high performance and security of SQL Server, although the storage efficiency will decrease.
6. make the MachineKey of all machines the same. configure in Machine. Config:

The code is as follows:


ValidationKey = "1234567890123456789012345678901234567890 AAAAAAAAAA"
DecryptionKey = "123456789012345678901234567890123456789012345678"
Validation = "SHA1"
Decryption = "Auto"
/>


(2) SqlServer mode:
1. objects to be stored in the Session can be serialized.
2. if the default database is used, the user of the database link string in the client configuration file must have the dbowner permission for the ASPState and tempdb databases.
3. in SQLServer mode, session expiration is completed by the SQL Agent using a registration task. make sure that the SQL Agent is running. Otherwise, the expired Session data cannot be cleared, resulting in a constant increase in database data.
4. if SqlServer mode is used, the ASP. NET application paths of servers in the Web farm must be the same. In the IIS configuration database, synchronize the Web application paths of all Web servers in the Web field. The case sensitivity must be the same, because the Web site application path is case sensitive.
5. make the MachineKey of all machines the same. configure in Machine. Config:

The code is as follows:


ValidationKey = "1234567890123456789012345678901234567890 AAAAAAAAAA"
DecryptionKey = "123456789012345678901234567890123456789012345678"
Validation = "SHA1"
Decryption = "Auto"
/>


(3) Session:
1. you cannot share sessions between ASP. NET and ASP directly through the Session server. please use the solution provided by Microsoft:
Http://msdn.microsoft.com/zh-cn/library/aa479313.aspx
2. Sessions cannot be shared between different applications or different virtual directories of a website.
3. the Session expiration time is the sliding time.
4. the Session storage. NET comes with the optimal value type performance. the storage object will reduce the performance.
(4) SessionID:
1. SessionID can also be saved on the URL. set the Cookiesless attribute of the System. Web/sessionState node in the Web. Config file:

The code is as follows:


Cookieless = "UseUri"
/>


2. generally, after the Session times out or is deleted, the SessionID remains unchanged. the Session will clear data on the server after it expires, but the SessionID is saved in the user's browser. as long as the browser is not closed, the SessionID in the HTTP header remains unchanged.
3. close the browser and try again. The SessionID will be different.
4. each time an IE6 window is opened, the SessionID is different. sessions in the two windows in IE6 cannot be shared.
5. the FireFox tab and the new FireFox window have the same SessionID. sessions can be shared in the FF window and tab.
6. for pages that contain FrameSet, such:

The code is as follows:








If the suffix is .htmparallel and the .htm file is not handed over to the ISAPI of ASP. NET for processing, different sessionids are generated on each Frame page based on the server speed, and the last SessionID is the same after refresh.
The final solution is to change the suffix of .htm to. aspx, and submit the. HTM file to the ISAPI of ASP. NET for processing.
(5) Session_End event:
1. Session_End is only available in InProc mode
2. close the browser and Session_End will not be triggered. HTTP is a stateless protocol, and the server cannot know whether your browser is closed.
3. when the Session expires or Session. Abandon is called, Session_End triggers. Session. Clear () to only Clear data but not delete the session.
4. Session_End is triggered by a background thread and runs with the worker process account. The program will not notify you of any errors.
5. when accessing the database from Session_End, you need to consider the permission issue. session_endruns with the account of the runtime worker (aspnet_wp.exe). This account can be specified in machine. config. Therefore, in Session_End, if you use integrity security to connect to SQL, it uses the identity of the worker process account to connect, which may cause logon failure.
6. because Session_End has an independent thread, you cannot use the HttpContext object (Request, Response, Server, and other objects in HttpContext) in Session_End, that is, you cannot use Response. redirect and Server. transfer and other methods.

VII. Summary
I have used SqlServer mode to share sessions among multiple servers in the company, and restarting the server will not cause the user to re-start the booking process (the Session required during the booking process will not be lost ). I hope this article will be helpful to the specific Session server setup personnel.

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.