Asp.net Session layer usage and management methods

Source: Internet
Author: User
Tags arrays define session exception handling generator http cookie memory usage session id serialization

1. Retain the default session module, but write a custom state provider to change the storage medium. In this way, we also have the opportunity to rewrite some helper classes used to carry session data between the storage and session.

2. Retain the default session module, but replace the session id generator.
3. Replace the default session status module with your own. This method provides the best flexibility, but it is also the most complex. We recommend that you use this solution only when you are sure to know the exact implementation method.
Build a custom session status provider
The session status provider is a component that serves the current session data. When a request requires status information, the component is called to obtain data from the specified storage medium and return the data to the master module. When the request ends, it is also called to write the provided data to the storage layer.
Asp tutorial. net supports three state providers. The following table describes them:
We can also write our own state provider class so that our applications can choose their preferred storage media.
Define session state storage
The status provider is a class inherited from sessionstatestoreproviderbase. The following table lists the main methods of its interfaces:
Inherit the sessionstatestoreproviderbase class and retain the default asp.net tutorial session status module. In this solution, you can only change the session status data storage and data recovery functions. Other functions cannot be changed.
Lock and expiration
The status provider must implement the locking mechanism for continuous session access. The session status module can determine whether the request requires read-only access in the session state or read/write access. Based on the judgment result, it will call getitem or getitemexclusive. In the implementation of these two methods, the compiler of the provider should create a locking mechanism for read/write sessions, allowing multiple concurrent read operations, however, you must prevent data from being written to a locked session.
Another problem is that the session status module needs to know the expiration time of a specified session. If global. asax defines the session_end event handler, the session status module calls setitemexpirecallback. By using this method, the status provider will get a callback function. Its prototype is as follows:
  
Public delegate void sessionstateitemexpirecallback (string sessionid, sessionstatestoredata item );
The session module stores the returned delegate internally and calls it when the specified session times out. Expired callback support is optional. In fact, only inproc actually supports it. If you do not want custom providers to support expiration callback, you should instruct the setitemexpirecallback method to return false.
To support providers without cookie sessions, you must also implement the createuninitialized method to write null session items to data storage. Specifically, an empty session item is a complete data item, but does not contain actual data. That is to say, the session item should contain the session id and creation time (which may also contain the lock id), but not the data. For asp.net 2.0, in non-cookie mode, a new id is generated when a request is sent after the session expires. Session status mode generates a new id and redirects the browser. If the uninitialized session item is not assigned a new id, the new request will still be considered as a request in an expired session.
Replacement of the session data dictionary
Sessionstatestoredata is a class that represents session items (a data structure that contains all session-related data ). In fact, instances of this class are returned by getitem and getitemexclusive. This class has three attributes: items, staticobjects, and tiemout.
Items is used to provide data for the key/value set in the session attribute of the page object. Staticobjects contains static objects that belong to the current session (for example, objects declared in global. asax and visible in the session range ). Timeout is the effective time (in units) of the session state. The default value is 20 minutes.
Once the session status module obtains the session status for the request, it writes the content of the items set to a new instance of the essionstatecontainer class in the https tutorial. The object is then passed to the constructor of the httpsessionstate class and becomes the data container behind the session attribute.
For the session module and status provider, the container of the session item is only a class that implements the isessionstateitemcollection interface. By default, the instance uses the sessionstateitemcollection class. As long as the custom class implements the preceding interface, it can replace the sessionstateitemcollection class.
To write a state provider, the sessionstateutility class is very useful. It contains methods for serializing and deserializing session items so that they can be stored in a media or read. In addition, this class also has some methods to extract data dictionaries from Sessions and add them to http context and session attributes.
Registration of the custom session status provider
To enable the application to use a custom session status provider, we need to register it in the web. config file. Assume that a provider class named samplesessionstaeprovider is compiled into a mylib Assembly:
  
<System. web>
<Sessionstate mode = "custom"
Customprovider = "samplesessionprovider">
<Providers>
<Add name = "samplesessionprovider"
Type = "samplesessionstateprovider, mylib"/>
</Providers>
</Sessionstate>
</System. web>
Custom Session id generation
To generate a session id, asp.net 2.0 uses the component sessionidmanager. This class is neither an http Module nor a program, but a class that inherits from system. object and implements the isessionidmanager interface. As long as the isessionidmanager interface is implemented, the custom class can replace this component.
Default behavior
The default session id module generates session IDs in the form of byte arrays and encrypts strongly random sequences with 15 values. The data is then encoded as a string containing 24 characters, and each character complies with the url standard. The system uses the session id.
The session id can be transmitted between the server and the client through an http cookie or a modified url, depending on the value of the cookieless attribute in <sessionstate>. Note: If a cookie-free session is used, the session id module is responsible for adding the id to the url and redirecting the browser. The default generator redirects the browser to the following virtual url:
Http://www.contoso.com/test/ (s (session_id)/page. aspx
How can requests from such URLs be correctly processed? In the absence of cookie sessions, the session id module uses a lightweight isapi filter (aspnet_filter.dll) to dynamically rewrite the input url to implement the resource url. The request will be processed correctly, but the path in the address bar will not change. The detected session id is placed in a header called aspfiltersessionid.
Self-made session id manager
Session id manager is a class that implements the isessionidmanager interface. Therefore, we have two solutions to build it:
1. Create a new class and implement this interface.
2. Derive a class from sessionidmanager and override two virtual methods (createsessionid and validate) to implement some special logic.
The isessionidmanager interface is described in the following table:
If you plan to use a fully custom session id generator, pay attention to the following points:
1. The algorithm for generating IDs is critical. If strong random encryption is not implemented, malicious users may guess valid IDs when some sessions are active. Therefore, generating a global guid is a good choice.
2. We can choose whether to support cookie-free sessions. If such support is added, the component must be able to extract session IDs from http requests and redirect the browser. Therefore, the isapi filter or http module may be required to pre-process the request and modify it as appropriate.
After creating the session id module, you can register it in the configuration file:
  

<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.
Related Article

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.