ASP. NET status management (cookie, session)

Source: Internet
Author: User
Tags send cookies set cookie ssl connection
ArticleDirectory
    • Cookie
    • Session status session
    • Session Architecture
    • Session Status
    • Configure session Status
    • Session status security
Cookie

Custom cookies provide another option to save backup data. Cookie creates a small file on your hard disk (the temporary cookie is saved in the memory of the Web browser ).

 

Cookie advantages:

    1. Transparent to users, they do not have to know what information needs to be saved.
    2. It is convenient for ApplicationsProgramAnd can be stored for a long time for different accesses.

Cookie restrictions:

    1. Like query strings, you can only use simple string information.
    2. If you find and open the cookie files, they are easily modified. Therefore, it is not suitable for storing complex, private information or a large amount of data.
    3. Some users disable cookies, but in most cases, users accept them because they are used by too many sites.

Cookie usage:

    1. Both the request object and the response object provide a set of cookies.
    2. Use the request object to read the cookie
    3. Set cookie using reesponse object
 
Httpcookie cookie =NewHttpcookie ("Preferences");

 
Cookie ["Language"] ="English";

 
Cookie ["Country"] ="Us";

 
Response. Cookies. Add (cookie );

 

The cookie added in this way will be sent back upon each request, and it will not disappear until the user closes the browser. But we canSet the expiration time to set the persistent cookie(A Temporary Internet file is stored on the user's hard disk ).

// This cookie lives for one year.

 
Cookie. expires = datetime. Now. addyears (1 );

 

Use the request. Cookies set to read the cookie by the cookie Name:

 
Httpcookie cookie = request. Cookies ["Preferences"];

 
 

 
// Because the user cocould disable cookie, so must check it

 
StringLanguage;

 
If(Cookie! =Null)

{

 
Language = cookie ["Language"];

 
}

 

The only way to remove a cookie is to replace it with an expired COOKIE:

 
Httpcookie cookie =NewHttpcookie ("Languagepref");

 
Cookie. expires =Datetime. Now. addyears (-3 );

 
Response. Cookies. Add (cookie );

 

 

Session status session

The most important part of session Status management! You can store data on one page and obtain data on another page. Most importantly, it also supports any object type, including custom data types. Each client accessing the application has different sessions and contains different information.Session is an ideal place to store the user's shopping cart content during cross-page browsing..

The session is not free. It forces the Web server to store additional information in the server memory. Even if the amount of information is small, hundreds of users may quickly cause a disaster when accessing the website.

 

Session Architecture

ASP. NET uses a unique 120-bit identifier to track sessions and uses a privateAlgorithmTo generate this value. Statistically, this value can be unique and random enough, so that malicious users cannot reverse design or guess the value to be used by the specified user.

This value is the unique value passed by the client and server.. After the client sends the session ID, ASP. NET searches for the corresponding session fromStatus ServerObtain the serialized data and convert it to the active object. Finally, place these objectsCodeThis process is automatically completed.

We know that ASP. NET processes HTTP requests through a pipeline chain containing different modules, which can respond to application events.One module on the chain is sessionstatemodule (in the system. Web. sessionstate namespace).

The sessionstatemodule is responsible for generating session IDs fromExternal providersAnd bind the data to the request context. After the page is processed, the module also saves session information. But it is important to understand that,Sessionstatemodule does not store session data, but persistence of session state in external components. These external components are called State providers..

 

Another example of ASP. NET pluggable architecture in session status. The status provider is any class that can implement the ihttpsessionstate interface. That is to say, to build (or buy) A new. NET Component, you can customize how to handle the session status.

ASP. NET hasThree pre-built status providersThey allow youProcess,Independent Service (Windows Service),SQL Server database.

 

Session Status

You can use the system. Web. sessionstate. httpsessionstate class to interact with the session state. It is established in the session object and provided by the ASP. NET webpage.

Session status is lost in the following situations:

    1. The user closes and restarts the browser.
    2. The user accesses the same page through another browser (different browsers process this method differently)
    3. No activity causes the session to time out. By default, the session will time out after 20 minutes of idle
    4. The programmer calls session. Abandon () to end the session.

In the first two cases, the session is actually stored in the server's memory. The web server does not know that the user has closed the browser or changed the window, and the session is wandering in the memory, however, it cannot be accessed until it expires. In addition, the session will be lost when the application domain is rebuilt, which is transparent.

 

Httpsessionstate Member:

Count Number of items in the current session set
Iscookieless Indicates whether the current session is stored in the cookie or embedded in the modified URL.
Isnewsession Indicates whether the session is created only for the current request
Mode An enumerated value that indicates how ASP. NET saves session status information.
Sessionid Session ID string of the current client
Staticobjects Usually not used (for backward compatibility with ASP programs)
Timeout Timeout duration. The value can be modified by code.
Abandon () Cancels the current session immediately and releases all the memory space it occupies. It is useful when you exit the page to ensure that the server memory is quickly reused.
Clear () Clear all session items without changing the current session identifier

 

 

Configure session Status

You can configure the session status for the application through the <sessionstate> element in the web. config file. The following is a quick view of all available settings:

 
<System. Web>

 
<! -- Other settings omitted -->

 
 

 
<Sessionstate

 
Mode= "Off | inproc | StateServer | sqlserver | custom"

 
Stateconnectionstring= "TCPIP = FIG: 42424"

 
Statenetworktimeout= "10"

 
Sqlconnectionstring= "Data Source = 127.0.0.1; Integrated Security = sspi"

 
Sqlcommandtimeout= "30" Allowcustomsqldatabase= "False"

 
Usehostingidentity= "Trye | false"

 
Compressionenabled= "True | false"

 
Cookieless= "Usecookies" Cookiename= "ASP. net_sessionid"

 
Regenerateexpiredsessionid= "True | false"

 
Timeout= "20"

Customprovider= ""

 
/>

 
</System. Web>

1. Mode

Mode settings allow youConfigurationTheSession status provider.

Off:

Disable session Status management for all pages in the Application

 

Inproc:

Similar to the traditional method of saving sessions in ASP, it instructs ASP. NET to save information in the current application domain. This method has the best performance but has the worst durability. If you restart the server, the status information will be lost. Inproc is the default option, which makes sense for most small websites, but cannot work in web clusters. You must use the SQL Server Status Service to share the session status between servers. Another reason for not using it is that it will generate a large number of session fragments. ASP.. NET applications will be recycled due to various activities, including configuration changes and page updates. If you find that your application domain is continuously restarted, Causing Premature session loss, you can choose another more robust session Status provider.

 

When using out-of-process or SQL Server Status services, remember to consider more issues:

    • When StateServer or sqlserver mode is used, the objects to be saved in the session state must be serializable. Otherwise, ASP. NET cannot transmit the objects to the status server or save them to the database..
    • In the cluster, some additional configurations are required to ensure synchronization between all Web servers. Otherwise, the server uses different methods to encode session status information, A problem occurs when a user routes data from one server to another. The solution to this problem is to modify the machine. the <machinekey> section of the config file to ensure that all servers use the same settings.
    • If you do not use the in-process status provider, the sessionstatemodule. End event will not be triggered. All the handlers registered with this event in the global. asax or HTTP module will be ignored..

StateServer:

With this option, ASP. NET uses an independent Windows Service to manage the status. Even if the web server is on the same server. It is also loaded outside the ASP. NET main process, so that when the ASP. NET process needs to be restarted, it can provide basic protection for the status.The cost is that the transmission of information between two processes will lead to latency. If the information is frequently accessed and changed, the speed will obviously slow down, making it intolerable..

When you use the StateServer option, you must set a value for stateconnectionstring. This value defines the TCP/IP address and port number of the computer running the service. Of course, you must start an application before it can use the service.

You can also set an optional statenetworktimeout feature when using the StateServer option. This feature specifies the maximum number of seconds to wait for the server to respond before giving up the request. The default value is 10 seconds.

 

SQL Server:

This option indicates that ASP. net uses the SQL Server database set by the sqlconnectionstring feature to save session information.This is currently the most elastic and slowest state storage method. To use this mode, you need a server with SQL server installed.. When setting sqlconnectionstring, you must specify the data source (server address). Unless you use the SQL integrated security mode, you must specify the user name and password. In addition, you need to install a temporary session database and some specific stored procedures. The stored procedure stores and obtains session information.

ASP. NET uses the command line tool aspnet_regsql.exe to achieve this goal. When using aspnet_regsqt.exe to create a session storage database, you must provide the-ssadd parameter. In addition, the-S parameter indicates the name of the database server. The-e parameter uses the Windows User Account currently logged on to log on to the database. Use the-ssremove parameter to remove the aspstate database..

This command creates a session storage database on the current computer and uses the default database name aspstate:

Aspnet_regsql.exe-s localhost-e-ssadd

This command uses the Kana localhost, which tells aspnet_regsql.exe to connect to the database server on the current computer. It can be replaced by the name of the computer where the database server is located.

Standard session Status timeout is also effective for SQL Server Status management. Because the aspnet_regsql.exe tool also creates a new SQL Server execution plan named aspstate_job_deleteexpiredsessions. The execution plan is executed once per minute as long as the SQLServerAgent service is running.

In addition, the status table is deleted every time you restart SQL Server, regardless of whether the session times out. This is because the table is created in the tempdb database and is a temporary storage area. If this is not your expected behavior, you can tell aspnet_regsql.exe to install the persistent state table in the aspstate database. This is the parameter-sstype P (persisted) that can be used)

Aspnet_regsql.exe-s localhost-e-ssadd-sstype P

Now, session records are stored in the database, even if SQL Server is restarted.

The last option is to create a non-default status table. In this case, use the-sstype C (custom) parameter and provide the database name through the-D parameter.

Aspnet_regsql.exe-s localhost-e-ssadd-sstype c-d mycustomstatedb

This method is used to create a persistent session table.

If a user-defined database is used, you also need to make two minor adjustments to Web. config:

<Sessionstate Mode= "Sqlserver" Allowcustomsqldatabase= "True" Sqlconnectionstring=

 
"Data Source = localhost; Integrated Security = sspi; initial catalog = mycustomstatedb" />

 

Custom:

When using the custom mode, you must use the customprovider feature to specify the session state storage provider. This feature points to the name of a class in the app_code folder, or the name of a compiled assembly in the bin directory or GAC.Creating a custom State provider is an underlying task that requires careful processing. To ensure security, stability, and scalability, it is best to design and test it by a reliable third party..

 

2. Compression

It can reduce the size of serialized session data. After the enablecompression is set to true, session data takes effect only when it is transferred to the off-process session state storage, because in this case the data will be serialized.

Session data is usedSystem. Io. Compression. gzipstreamClass automatically compressed.

The following are the two most meaningful scenarios for session state compression:

    • When a large amount of session status data is stored in the memory: Web server memory is a very precious resource. Ideally, the session state is used for a small amount of information segments, and the backend database processes a large amount of data for long-term storage. However, if this is not the case, and the server in the out-of-process state has a large amount of memory, there is a potential compressed solution.
    • When other computers store session status data: In some large Web applications, the session state is outside the process (generally SQL Server) and on a separate computer. Therefore, ASP. NET needs to transmit session information over a network connection. Obviously, this design reduces the execution speed. However, this is still the best compromise for some websites that require a large amount of session status information and have a large traffic volume.

First, compression sacrifices the CPU time in exchange for the Web server memory.

In the second case, compression sacrifices the CPU time to save network traffic.

Note:

The actual compression volume varies greatly depending on different data types. However, in Microsoft's tests, the client reduced data by 30% to 60%, in these scenarios, the performance is greatly improved.

 

3. cookieless:

Enumerated values of httpcookiemode:

Usecookies You can always use cookies (the default option) regardless of whether the browser or device disables cookies ).
If the device does not support cookies, the subsequent request session information will be lost, because each request will obtain a new identifier.
Useuri Cookies are not used regardless of whether the browser or device supports cookies. The session ID is stored in the URL.
Usedeviceprofile ASP. NET checks the browsercapabilities object to determine whether to use a non-Cookie Session.

(Only indicates what the device should support-without considering that the user may disable cookies in the browser)
Autodetect ASP. NET checks whether the browser supports cookies by setting and reading cookies (a common web technology ).

This technology can correctly determine whether the browser supports cookies but disables cookies. In this case, no Cookie Session is used.

 

When using the cookieless mode, such as the following:

<Sessionstate cookieless = "useuri"...>

The session ID is automatically inserted into the URL. When ASP. NET receives the request, it will remove the ID, retrieve the session set, and send the request to the corresponding directory:

Http: // localhost/webapplication/(amfdddgd677sdgfdfg)/page. aspx

Because the session ID is inserted into the URL, the relative link will automatically obtain the session ID,What really limits the cookieless session status is: absolute links cannot be used because they do not contain session IDs..

 

ASP. NET allows reuse of session IDs by default. If a query string containing an expired session is used, ASP. NET will use this ID to recreate a session. The problem is that a session ID may appear inadvertently in some public scenarios, such as search engine query results. In this way, multiple users use the same session ID to access the server and add it to the same session with the same shared data.To avoid this potential security problem, we recommend that you add the optional regenerateexpiredsessionid feature when using a cookieless session and set this value to true. In this way, when you use an expired session ID, a new session ID will be created.. The only drawback of this is that all the view status and form data on the current page will be lost, because ASP. NET executes a redirection to ensure that the browser uses the new session ID.

You can use the iscookieless attribute of the session object to check whether a session without a cookie is currently in use.

 

4. Timeout

This setting reflects the most important compromise of the session state. Different minutes will significantly affect server load and application performance. Ideally, the best time should be short enough to ensure that the server memory can be released in a timely manner. At the same time, this time should be long enough, ensure that the client can continue to use the service after it is paused for a period of time without losing the session.

You can set in the Code:

Session. Timeout = 10;

 

 

Session status security

The information in the session status is very secure because they are only stored on the server. However, cookies containing session IDs may be easily tampered. That is to say, a malicious user can steal the cookie and continue using it on another computer.

A common method is to use a custom session module to check the IP address changes of the client. The only valid method is to use session cookies only on websites that use SSL. In this way, session cookies are encrypted and thus unavailable on other computers.. If this method is used, it makes sense to identify the session cookie as a secure cookie, so that the cookie can only be transmitted through an SSL connection. This makes it impossible for users to change the URL from https: // to http: // that can send cookies without using SSL ://.

Request. Cookies ["ASP. net_sessionid"]. Secure = true; // such cookies must be transmitted on websites that use SSL.

This code should be used immediately after the user passes the verification. In addition, make sure that there is at least a bit of information in the session state so that it will not be canceled.

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.