Understanding asp.net session state
Author:Eve Cole
Update Time:2009-07-01 16:44:49
1. Functions of session state
HTTP is a stateless protocol, so it does not automatically indicate whether a sequence of requests are all coming from the same client, or even whether a single browser instance is still actively viewing a page or site. And using the built-in session state function of ASP.net, we can use
1. Automatically identify and classify requests from a single browser client to a logical application session on the server.
2. Store session-scoped data on the server for use across multiple browser requests.
3. Raise appropriate session lifetime management events (Session_OnStart, Session_OnEnd, etc.) that can be handled in application code
2. Identification of session status
When creating a session, the server generates a separate ID for each session. The identifier is represented by a 120-bit SessionID string that contains only the ASCII characters allowed in the URL. The SessionID value is generated using an algorithm that guarantees uniqueness and randomness. The purpose of guaranteeing uniqueness is to ensure that sessions do not conflict, and the purpose of guaranteeing randomness is to ensure that malicious users cannot use new SessionIDs to calculate the number of existing sessions. SessionID.
3. How to store session state
There are three ways to store session state:
1. In-process session state mode (Inproc): When we create a new Web program, the in-process session state mode is adopted by default. This is also the mode commonly used by everyone. In this mode the session state is stored locally in the ASP.NET worker process, so by far the in-process session state mode is probably the fastest access option. But the more data stored in a session, the more memory the web server consumes, potentially increasing the risk of performance degradation.
2. .NET state server mode (StateServer): The session state is stored in the remote process (for example, in the windows NT service named aspnet_state.exe)
3. SQL mode (SQLServer): Session state is stored in a dedicated database table managed by SQL Server.
Both .NET state server mode and SQL mode can be called out-of-process session mode. When storing data, the data needs to be serialized and stored in an external repository. When reading and data, the data needs to be deserialized and copied to the local session dictionary, so the request resulted in performance degradation of 15% (out-of-process) to 25% (SQL Server). Note that this is only a rough estimate. But in the out-of-process storage scenario, session state survives longer, making the application more powerful because it protects against Microsoft® Internet Information Services (IIS) and ASP.NET failures. By separating session state from applications, you can also more easily extend existing applications into Web Farm and Web Garden architectures. Additionally, session state is stored in an external process, essentially eliminating the risk of periodic data loss due to process loops.
4. Configuration of session state
The configuration of session state is achieved by setting the <sessionState> section of the Web.config file. The following introduces the specific configuration methods of the three session states.
1. In-process mode
In-process mode is the default session state mode. To use in-process mode, set the mode attribute of the <sessionState> element to Inproc.
An example configuration setting for in-process mode is shown below. http://www.downcodes.com
<configuration>
<system.web>
<sessionState mode="Inproc"
cookieless="false"
timeout="20"/>
</sessionState>
</system.web>
</configuration>
2. State server mode
To use a state server, you must first ensure that the ASP.NET state service is running on the remote server used for session storage. This service is installed with ASP.NET and Visual Studio .NET at:
systemrootMicrosoft.NETFrameworkversionNumberaspnet_state.exe
Then, in the application's Web.config file, set the mode attribute of the <sessionState> element to StateServer. Finally, set the connectionString property to tcpip=serverName:portNumber.
The following is an example of configuration settings for state server mode.
<configuration>
<system.web>
<sessionState mode="StateServer"
stateConnectionString="tcpip=dataserver:42424"
cookieless="false"
timeout="20"/>
</sessionState>
</system.web>
3. SQL Server mode
To use SQL Server, first run InstallSqlState.sql or InstallPersistSqlState.sql on the SQL Server computer where session state will be stored. Both scripts create a database named ASPState, which contains several stored procedures.
The difference between the two scripts is where the ASPStateTempApplications and ASPStateTempSessions tables are placed. The InstallSqlState.sql script adds these tables to the TempDB database, which will lose data when the computer is restarted. Instead, the InstallPersistSqlState.sql script adds these tables to the ASPState database, which allows session data to be preserved across computer restarts.
By default, both script files are installed in the following location:
systemrootMicrosoft.NETFrameworkversionNumber
Then, in the application's Web.config file, set the mode attribute of the <sessionState> element to SQLServer. Finally, set the sqlConnectionString property to Integrated Security=SSPI;data source=serverName;.
An example configuration setting for SQL Server mode is shown below.
<configuration>
<system.web>
<sessionState mode="SQLServer"
sqlConnectionString="Integrated Security=SSPI;data source=dataserver;"
cookieless="false"
timeout="20"/>
</sessionState>
</system.web>
</configuration>
In SQL Server mode, session state can also be configured to work in a failover cluster. A failover cluster is two or more identical redundant Web servers that store session data in a SQL Server database on a separate computer. If one Web server fails, another server in the cluster takes over its work and serves requests without losing session data.
To configure failover clustering, set the <machinekey> element in the Web server's Web.config file to the same value.
Then set the Web server's SQL connection string to point to the SQL Server database on your computer where the session data is stored.
5. Access to session state
You can access session state directly through the Session collection. For compatibility with earlier versions of ASP, access to session state can also be achieved through the Session.Contents property on the application object.
The following example shows writing two values to the Session collection on the first web page, and then reading the Session collection on the second web page. Note: Page codes are omitted here.
The first web page, writes the value to the Session collection
dim name as string = "a"
dim id as integer = "1"
session("name") = name
session("id") = id
The second web page gets the value from the Session collection
dim name as string = session("name")
dim id as integer = session("id")
'Get the number of items in the session state collection
dim i as integer = session.count
Note that in in-process mode, no real serialization and deserialization occurs, so the objects are stored in session state as active instances of their respective classes.
In the out-of-process session mode, because serialization and deserialization are used, you have to convert the data type according to the situation.
If you are serializing a date value, the date should be of type Int64.
6. Session lifetime management events
There are two session lifetime management events, Session_OnStart event and Session_OnEnd event. You can set them in the Global.asax.VB file.
1. Session_OnStart event
When a single browser client connects to the server, the Session_OnStart event is triggered, which marks the beginning of the session. This event will no longer be triggered during subsequent browsing unless the session times out or is abandoned. The Session_OnStart event is the best time to set session variables because they are set before any page is accessed.
Example: The following example is a commonly used Session_OnStart event code for counting the number of people online:
Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
'When an event occurs, add 1 to the number of online users
Application("usercount") = Application("usercount") + 1
End Sub
2. Session_OnEnd event
The Session_OnEnd event occurs when a session is abandoned or times out, and it marks the end of the event. But please note that this event is only supported in InProc mode. You can specify the timeout period through the timeout attribute of the <sessionState> section of the Web.config file. If the user is within the timeout period (in minutes, the default is 20 minutes
clock) without refreshing or requesting the web page, the session will be terminated. You can use the Session_OnEnd event to do some cleanup work.
Example: The following example is a commonly used Session_OnEnd event code for counting the number of people online:
Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
Application("usercount") = Application("usercount") - 1
End Sub