<Sessionstate sessionidmanagertype = "samples. myidmanager, mylib">
</Sessionstate>
Use
The session status module manages the execution of all these tasks. Therefore, it also needs to use two components: Session id generator and session status provider. In asp.net 2.0 and later versions, the two can be replaced by custom components.
Session ID
Each active asp.net session is identified by a 15-byte (120-bit) string, containing only url-compliant characters. Session IDs are randomly generated and unique to avoid malicious attacks and data conflicts. It is almost impossible to use an algorithm to calculate a valid session id from an existing id.
Session id generation
The session id is 15 bytes in length and is generated by the random number generator (rng) password provider. The service provider can return 15 random numeric sequences, which are mapped to valid url characters and returned as strings.
If the session does not contain any data, each request will receive a new session id, but the session status will not be saved by the status provider. However, if you set the session_start event handler, the session state will always be saved (even if it is empty ). Therefore, the handler that defines the session_start event should be cautious, especially when the in-process session provider is not used.
On the contrary, if the session dictionary is not empty, the session id will be retained after it times out or is abandoned. According to the design, even if the session status is outdated, the session id continues until the browser session ends. This means that, as long as the browser instance remains unchanged, the same session id will be used to represent multiple existing sessions at the same time.
Session cookie
Between the browser and the server, the sessionid string is transmitted in two ways: cookie or modified url. By default, the session status module creates an http cookie on the client, but the modified url can be embedded with the sessionid string (this method is especially suitable for non-cookie browsers) the method to use depends on the method stored on the web. in the config file, the cookie scheme is used by default.
In fact, cookies are nothing more than text files associated with web pages on the client's hard disk. In asp.net, cookies are represented by httpcookie instances. Generally, the cookie data protection name, the set of values, and the Expiration Time. In addition, you can configure the virtual path of the cookie and choose whether to transmit the cookie through a secure connection (such as https.
Asp.net 2.0 and later use the http-only session cookie support of the browser. Computers that install ie 6.0 sp1 and winxp sp2 are supported. Http-only can prevent client scripts from using cookies, thus reducing the potential risk of cross-site scripting attacks to steal session IDs.
If cookie is enabled, the session status module creates a cookie with a specific name and stores the session id in it. The cookie creation process is as follows:
Httpcookie sessioncookie;
Sessioncookie = new httpcookie ("asp.net _ sessionid", sessionid );
Sessioncookie. path = "/";
Asp.net _ sessionid is the cookie name, and sessionid is the value. The cookie is also associated with the root of the current domain. The path attribute is used to describe the relative url of a cookie. Session cookies are assigned a very short expiration time and updated after each request is successfully completed. The expires attribute of the cookie object is used to indicate the number of days when the client cookie expires. If there is no explicit setting, the expires attribute defaults to datetime. minvalue, that is, the shortest time defined in. net, just like session cookie.
To write a cookie to the server module, you must add an httpcookie object to the response. cookies set. All cookies associated with the requested domain discovered on the client will be uploaded to the server, and can then be read through the request. cookies set.
No cookie session
To make the session status work normally, the client must be able to upload the session id to the server application. The specific details of this process depend on the application configuration. The asp.net application defines session-specific settings through the <sessionstate> configuration file. The cookie support method is determined. We need to set the cookieless attribute to a value in the following table. These values are of the httpcookiemode enumeration type:
When cookie support is disabled, it is assumed that the user requests a page through such a url:
Http://www.contoso.com/test/sessions.aspx
The address displayed in the address bar of the browser changes (including the session id) as follows:
Http://www.contoso.com/test/ (s (sylgasdfueoruikfjoiueriljk)/sessions. aspx
When the session status module is instantiated, it checks the cookiesless attribute value. If the cookie is disabled, the request is redirected to a modified virtual url (http status code 302 ), it contains a session id, which is just before the page name. When the request is processed again, the session id is embedded in the request. This request is pre-processed by a special isapi (aspnet_filter.exe component) to parse its url. If it contains a session id, it is rewritten to the correct url. The detected id is stored in an individual http header (aspfiltersessionid) for later use.
Problems caused by cookieless sessions
When a session starts, no cookie is triggered, regardless of whether the user sends an absolute url of the application page or not.
If you use cookies and enter the address of another application in the address bar, the same session value is obtained when you return to the previous page. If the cookie is disabled, it is automatically implemented through the relative url when the page is sent back, and will not be affected. However, if you use an absolute url link, session data will be lost. In this case, a new session will always be created. For example, the following code interrupts the current session:
<A runat = "server href ="/test/sessions. aspx "> click </a>
Is there any way to automatically modify the absolute url in the link and hyperlink to integrate it into the session id information?
We can use the applyapppathmodifier method of the httpresponse class:
<A href = '<% = response. applyapppathmodifier ("test/page. aspx") %>'> click </a>
The applyapppathmodifier method accepts a string representing a relative url and returns an absolute url with session information. This technique is very suitable for redirecting an http page to an https page. The Complete absolute address must be used. Note: If the session cookie is enabled or the input path is absolute, applyapppathmodifier returns the original url.
We cannot use the <%... %> code block in a server expression (that is, an expression with the runat = server attribute. This code block works in the preceding code because the <a> label is plain text and does not have the runat attribute. Note that the code block mentioned here has nothing to do with the data binding expression <% #... %>. The reason why the <%... %> code block cannot be used in server expressions is that the runat attribute instructs you to forcibly create the current tag as a server object, which is not processed by server objects.
Cookie-free session and security
Another problem caused by the use of cookieless sessions is related to security. Session hijacking is one of the most common attack types. It generates a session id of another legal user to access the external system. To understand this attack method, you can configure the application to not use cookies, access a page, and obtain the url with the session id (which can be taken from the address bar of the browser ), and immediately send an email to a friend. Paste the url to the address bar of your browser and click "Go ". As long as your sessions are active, your friends can also access the same session.
For the sake of system security, it is critical to generate a random id, because this makes it difficult for attackers to guess a valid session id. For non-cookie sessions, the session id is exposed in the address bar and visible to the outside world. Therefore, if you want to store private or sensitive information in a session, we recommend that you use either the secure sockets layer (ssl) or transport layer security (transport layer security, tls) encrypts the communication between the browser and the server that contains the session id.
In addition, if the user thinks this will reduce security, we should also provide the logout Function for it and call the abandon method. This will shorten the time for an attacker to find a valid user's session id. In addition, from the security perspective, it is necessary to configure the application to avoid repeated use of expired session IDs when using a non-cookie session. In asp.net, this behavior can be configured through the <sessionstate> section.
Session status configuration
During the transition from asp.net 1. x to asp.net 2.0, the <sessionstate> section option is also added, as shown below:
<Sessionstate
Mode = "off | inproc | stateserver | sqlserver | custom"
Timeout = "number of minutes"
Cookiename = "session cookie name"
Cookieless = "http cookie mode"
Regenerateexpiredsessionid = "true | false"
Sqlconnectionstring = "SQL connection string"
Sqlcommandtimeout = "number of seconds"
Allowcustomsqldatabase = "true | false"
Usehostingidentity = "true | false"
Partitionresolvertype = ""
Sessionidmanagertype = "custom session id generator"
Stateconnectionstring = "tcpip = server: port"
Statenewworktimeout = "number of seconds"
Customprovider = "custom provider name">
<Providers>
...
</Providers>
</Sessionstate>
The attributes of sessionstate are described in the following table:
In addition, the sub-section <providers> user sets all the custom session state storage providers.
Session lifetime
The lifetime of the session state starts when the first data item is added to the dictionary in the memory. This dictionary is an internal class instance of sessiondictionary.
Session_start event
The session startup event is irrelevant to the session status. The session_start event is triggered when the session status module provides services for the user's first request and requires a new session id. The asp.net runtime library can serve multiple requests in a single session context, but only the first request will trigger the session_start event.
If no data is written to the dictionary, a new session id is created on the request page and the session_start event is triggered.
Session_end event
The session_end event is used to notify the end of a session and execute the cleanup code involved in terminating the session. However, it should be noted that this attribute must be in inproc mode currently (session data is stored in asp.net worker threads ).
To enable session_end triggering, the session status must already exist in advance. This means that we must store some data in the session state and complete at least one request. When the first value is added to the session dictionary, a corresponding item is inserted into the asp.net cache. This action targets the in-process status provider. Both the out-of-process status server and the SQL server Status service do not involve cache objects.
The session status item added to the cache will be specified with an adjustable Expiration Time (the interval in the session timeout setting), as long as a request is processed in the context of the current session, the adjustable time is automatically updated. The session status module resets this timeout setting when processing an endrequest event. This module can achieve the expected results by performing a read operation on the cache. The internal structure of the asp.net cache object so that it can estimate the length of the adjustable period. Therefore, when the cache item expires, the session status also times out.
Expired items are automatically removed from the cache. As part of the expiration policy, the session status module also specifies a callback function to be removed. The removed function is automatically called by the cached object, which triggers the session_end event.
Items in the cache that represent the session state cannot be accessed outside the system. web assembly, and enumeration cannot be performed because they are placed in the cache system reserved area. That is to say, we cannot access the data located in another session programmatically, so removing the data will not be a problem.
Why is session status sometimes lost?
The values in the session object can be removed programmatically or removed by the system when the session times out or is abandoned. But in some cases, the session status may be lost inexplicably. Why?
In inproc mode, the session state is mapped to the appdomain memory space that processes the current request. Therefore, the session status is affected by process recovery and appdomain restart. The asp.net worker thread restarts periodically to maintain overall good performance. After the restart, the session status will be lost. The execution of process recycling will be based on the memory usage and the number of requests to be processed. Although the process is cyclical, it is impossible to estimate the recovery interval. Therefore, this issue should be fully considered when designing session-based, in-process applications. The session status may not exist during access attempts. When exception handling or recovery is used, it should be analyzed based on specific applications.
What is the impact on the session status when a page is running incorrectly? Will the current session dictionary be saved or lost? If an error occurs at the end of the request (the getlasterror method of the server object returns an exception object), the session status will not be saved. However, if you call the server. clearerror method in the exception handling program to reset the exception status, the session status data will be saved as normal, just as there is no error.
Save the session status on the remote server
You can use the out-of-process status provider to solve the problem of session status loss in inproc mode. However, if the session status is not stored in the asp.net workflow, an additional layer of code is required to serialize and deserialize the data in the storage media. This operation takes place during the request processing process.
Copying session data from an external store to a local session dictionary may result in a 15%-25% reduction in the performance of the state management process.
If you select a non-process status provider, you should consider creating a runtime environment before the application enters the production environment. This involves enabling the stateserver windows service or configuring the sqlserver database tutorial.
Status serialization and deserialization
If inproc mode is selected, the objects stored in the session state are class instances, and no serialization or deserialization is required. We can store any objects created by developers in the session state, and there is no additional overhead to access them. However, if you select an out-of-state provider, the situation is quite different.
In an out-of-process architecture, session values need to be copied from the original storage medium to the memory of the appdomain processing the request. This requires serialization/deserialization, which is one of the main overhead of the off-Process state provider. So what is the impact of our code? First, we should ensure that only serializable objects are stored in the dictionary.
In terms of serialization and deserialization, asp.net has two methods with different performance. For basic types, asp.net uses an optimized internal serialization program. For other types, asp.net uses the. net binary formatting program, which is slow.
The optimized serialization program (an internal class called altserialization) will use the binarywriter object, first writing bytes representing the corresponding "type" and then its value. During reading, the altserialization class will first extract a byte to determine the type of the data to be read, and then read the specific value using the type-specific method in the binaryreader class. Each type is associated with an index value based on an internal table.
The size of Boolean and data types is fixed, while the length of a string is variable. So how does the reader determine the length of a string? The binaryreader. readstring method utilizes the following technique: in the bottom layer, a string always carries a length prefix. For the datatime type, this method is written in the form of the total number of scales of the date and time, and is read as the int64 type.
For a complex object, as long as it is marked as "serializable", it will be serialized through the binaryformatter class, and its speed is relatively slow. Simple and complex types use the same stream, but all non-basic types are identified by the same type id.
We should not store any objects in the session. If you use an out-of-process solution, exercise caution when storing dataset. This is related to the serialization process of the dataset class. Because dataset is a complex type, it is serialized through a binary formatting program. The serialization of dataset itself will generate a lot of xml data, which will cause serious defects to applications, especially for large applications that store large amounts of data.
Session Data storage
Secret's microsoft windows nt service. This service is used to serialize the session status at the end of the request. Internally, the service uses byte arrays to store the status of each session. If you start to process new requests, the array corresponding to the given session id will be copied to the memory stream and deserialized into an internal session status item object. This object represents the content of the entire session. The actual httpsessionstae object used on the page is only its application programming interface.
Stateserver provider configuration
If the out-of-process storage scheme is used, the session state will be delayed. In this way, the application is more robust. By separating session states from pages, we can also gradually convert existing applications to the web farm and web garden architectures.
Asp.netsession state handler is a windows service named aspnet_state.exe. The executable file of this service is located in the installation folder of asp.net: % windows % microsoft. netframework [version].
Note that the specific path depends on the version of the. net framework that is actually running. Before using the status service, ensure that the service runs properly locally or on a remote computer used to store sessions.
We need to specify the IP address of the computer on which the session status service is run for the asp.net application. To enable the remote session status, we need to configure in web. config:
<Configuration>
<System. web>
<Sessionstate mode = "stateserver"
Stateconnectionstring = "tcpip = mymachine: 42424"/>
</System. web>
</Configuration>
The server name can be either an IP address or a computer name.
The status server does not set any authentication barriers for the requester, so that the network user can freely access session data. To protect the session status, make sure that it can only accept access from web server computers. Therefore, we can use the firewall, ipsec policy, or security Network 10. x, so that external attacks cannot be directly accessed. You can also modify the service port of the registry by modifying the key value "hkey_local_machinesystemcurrentcontrolsetservicesaspnet_stateparameters.
The asp.net application immediately tries to connect to the session status server after loading. Status service uses. net remoting for data communication.
By default, the status server only listens to local connections. If the status server and the web server are different computers, we need to enable remote connections. Therefore, you only need to modify the key value "hkey_local_machinesystemcurrentcontrolsetservicesaspnet_stateallowremoteconnection" in the registry and set it to a non-zero value.
Save data to SQL server
If the application has high robustness requirements, for example, after the status provider service is disabled, data will not be lost, you may wish to use the SQL server service.
If asp.net works in SQL server mode, session data is stored in a dedicated database table. Therefore, even if SQL server crashes, session data will not be lost, but this requires higher system overhead.
To use SQL server as the status provider, you need to configure the web. config file:
<Configuration>
<System. web>
<Sessionstate mode = "sqlserver"
Sqlconnectionstring = "server = 127.0.0.1; integrated security = sspi;"/>
</System. web>
</Configureation>
If you do not enable a custom database through allowcustomsqldatabase, the connection string cannot contain settings such as database and initial catalog. Only when the allowcustomsqldatabase setting is enabled can the database name be specified through database and initial catalog.
The connection string can also be referenced and defined in the <connectionstring> Section. The connection string name can be specified in the <sessionstate> attribute.
The access creden to the database can be provided by the user ID and password, or by using "Integrated Security ". Regardless of the account used to access the session status in SQL server, ensure that the user has at least db_datareader and db_datawriter permissions. It should also be noted that administrator permissions are required to configure the SQL server environment for storing session status, because new databases and stored procedures need to be created.
For the session status in SQL server mode, we can specify the sqlcommandtimeout attribute of the custom command (in seconds) for setting.
SQL server database creation
Asp.net provides two pairs of scripts used to configure the database environment, so as to create necessary tables, stored procedures, triggers, jobs, and so on.
The first script is installsqlstate. SQL and uninstallsqlstate. SQL. They can create an aspstate data and several stored procedures, but the data is stored in several tables in the tempdb database. In this way, if the computer in which SQL server is located is restarted, session data will be lost.
The other scripts are installperisistsqlstate. SQL and uninstallperisistsqlstate. SQL. The difference from the first script is that the tables they create are persistent in the aspstate database. There are two tables named aspstatetempapplications and aspstatetempsessions.
All scripts can be found in the following path:
% Systemroot % microsoft. netframework [version]
These scripts are only backward compatible. We should use aspnet_regsql.exe to install and uninstall the SQL session status.
Each currently running asp.net application corresponds to a record in the aspstatetempapplications table. The following table describes the columns in the table:
The aspstatetempsessions table is used to store actual session data. Each active session corresponds to a record in the table. The following table describes the structure of the table:
When SQL server supports session installation, another job is added to delete expired sessions from the session status database. The job name is aspstate_job_deleteexpiredsessions. The default configuration is to run once per minute.