Session and cookie in ASP. NET

Source: Internet
Author: User
Tags cookie names
Session:

Session indicates a "session". However, because the HTTP protocol is stateless, each time the client requests the server, the server will display a "new" page to the client, this does not affect static html pages. However, in dynamic pages, you need to interact with users. To maintain contact with client users, you need something to maintain, in session mode, session persistence is enabled.

Note that sessions are stored on the server. (Cookies are stored on the client.) Note that if the user suddenly closes the client page, the session will be lost, that is, the session will be lost ".

 

Three steps for creating a session on the server side (for more information, see online ):

1. Generate a globally unique identifier (sessionid );

2. Open up data storage space. Generally, the corresponding data structure is created in the memory, but in this case, once the system loses power, all session data will be lost. If it is an e-commerce website, such accidents can cause serious consequences. However, it can also be written to a file or even stored in a database, which increases the I/O overhead, but the session can be persisted to some extent and is more conducive to session sharing;

3. Send the Globally Unique Identifier of the session to the client.

The key to the problem lies in how the server sends the unique identifier of the session. After connecting to the HTTP protocol, data can be stored in the request line, header domain, or body. Based on this, there are generally two common methods: Cookie and URL rewriting.

1. Cookie (sessionid will be saved in the cookie and the expiration time is 0, which is the validity time of the browser process. If the browser is closed, the session will become invalid. The principle is as follows)

The reader should have thought of it. Yes, the server only needs to set the set-Cookie header to send the session identifier to the client. This identifier will be included in each subsequent request of the client, because the cookie can set the expiration time, generally, the cookie containing session information sets the expiration time to 0, that is, the browser process validity time. As for how the browser handles this 0, Each browser has its own solution, but the difference is not too big (usually reflected in the creation of a browser window );

2. URL rewriting? Sessionid = XXXX)

URL rewriting, as its name implies, is URL rewriting. Imagine that before returning a user request page, add the session identifier (or add the session identifier to the Path Info part) to all the URLs in the page as the get parameter ), in this way, after receiving the response, no matter which link you click or submit the form, the user will carry the session identifier, thus realizing session persistence. Readers may think this approach is troublesome, but it is true. However, if the client disables cookies, URL rewriting will be the first choice.

 

Basic usage of session in ASP. NET

When defined: session ["DDD"] = xxxx;

When used: session ["DDD "]

If you want to save the class object, the usage is the same as viewstate:

Sender:

Userinfo UI = new userinfo ();
Session ["UI"] = UI;
Ui. Name = Name. text;
Ui. Age = age. text;
Ui. Sex = sex. text;
Ui. Password = password. text;
Response. Redirect ("A. aspx ");

Acceptor:

Userinfo UI = session ["UI"] As userinfo;
Name. Text = UI. Name;
Age. Text = UI. Age;
Password. Text = UI. Password;
Sex. Text = UI. sex;

 

Session time (destruction method: time-out and manual destruction ):

The default Asp.net session time is set to 20 minutes. That is, after 20 minutes, the server automatically discards the session information.

 

Session hijack (for online reference ):

Session hijack is a serious security threat and a widespread threat. In session technology, the client and server maintain sessions by transmitting session identifiers, however, this identifier can be easily sniffed and exploited by others. This is a man-in-the-middle attack.

 

Cookie

The biggest benefit of cookie is the "remember me" service.

The cookie is stored on the client. If the cookie is disabled, there may be some problems. Therefore, pay attention to the design (determine whether the cookie is null)

The reason for cookie is the same as that for session. Because the HTTP protocol is stateless, every time a new page is created, no information is saved, and the cookie is saved on the client's computer, when necessary, you can use the backend server or the client.

Cookie is only a piece of text, so it can only save strings. In addition, the browser has a size limit on it and it will be sent to the server with each request, so it should be ensured that it should not be too large. Cookies are stored in plain text. Some browsers provide interface modifications. Therefore, it is not suitable for storing important or private content. (Online reference)

 

Cookie restrictions:

Most browsers support a cookie of up to 4096 bytes. Because this limits the cookie size, it is best to use cookies to store a small amount of data or user IDs. User IDs can then be used to identify users and read user information from databases or other data sources. The browser also limits the number of cookies that the site can store on the user's computer. Most browsers only allow 20 cookies per site. If you try to store more cookies, the oldest cookies will be discarded. Some browsers impose absolute limits on the total number of cookies they will accept from all sites, typically 300.

 

Cookie attributes: (for more information, see)

Name: Each cookie is represented by a unique name, which can contain letters, numbers, and underscores. The cookie name is case-insensitive, so mycookie and mycookie are the same. However, considering that the server language may be case sensitive, we recommend that you define and use the language in case sensitive mode.

Value: the string value stored in the cookie. Before storing this value, you must use encodeuricomponent () to encode it to avoid data loss or cookie occupation. Note: The sum of cookie names and values cannot exceed 4095 bytes, that is, 4 kb.

Domain: For security reasons, websites cannot access cookies created by other domains. After a cookie is created, the domain information is stored as part of the cookie. For the domain, here is an example, such as the http://ibm.com/foo/index.aspx, whose domain is: ibm.com.

Path: another security feature of cookie, which limits access to a specific directory on the Web server. That is, control which access can trigger sending. for example, the request URL is the above URL. If Path =/Foo, the cookie will be sent, but if path is other, the cookie will be ignored.

Expires: Cookie expiration time.

Secure: A value of true/false to indicate whether a cookie can be accessed only from a secure website (a website using SSL and HTTPS protocols. If this value is set to true

 

 

Cookie basic steps: (for more information, see)

Steps for the browser to respond to the cookie in the web server:

A. Extract all cookies from the response header of the Web server.

B. parse the components (names, values, paths, and so on) of these cookies ).

C. Determine whether the host allows these cookies. If yes, these cookies are stored locally.

To filter all the cookies in the Web Server Request Header:

A. Determine which cookies can be sent to the Web server based on the request URL and the local cookie storage attributes.

B. Determine the sending sequence for multiple cookies.
C. Add the cookie to the HTTP packet header for sending.

 

Basic usage of cookies in ASP. NET:

Sender:

Httpcookie cookie = new httpcookie ("userinfo ");

Cookie ["name"] = Name. text;

Cookie ["Age"] = age. text;

Cookie ["sex"] = sex. text;

Cookie ["language"] = language. text;

Cookie. expires = datetime. maxvalue;

Response. Cookies. Add (cookie );

Response. Redirect ("cookie2.aspx ");

Acceptor:

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

If (cookie! = NULL)

{

Name. Text = cookie ["name"];
Age. Text = cookie ["Age"];
Language. Text = cookie ["language"];
Sex. Text = cookie ["sex"];

}

Else

{}

It is best to add a condition judgment on the acceptor to avoid errors if the cookie is disabled. You can also determine whether the cookie exists.

 

Cookie usage:

Prevent repeated online voting;
Automatic Login using cookies
Single Sign On (SSO) is one of the most popular solutions for enterprise business integration. simply put, in multiple application systems, users only need to log on once to access all mutually trusted application systems. It includes a mechanism for ing the main logon to other applications for the login of the same user.

 

 

Session and cookie comparison: (online reference)

1. application scenarios

A typical application scenario of cookie is the remember me service, that is, the user's account information is saved on the client in the form of cookies. When the user requests a matching URL again, the account information will be sent to the server and handed over to the corresponding program for automatic login and other functions. Of course, you can also save some client information, such as page layout and search history.

A typical application scenario of session is that a user logs on to a website and puts the user's logon information into the session. In each subsequent request, the user can query the corresponding logon information to ensure that the user is valid. Of course, there are still classic scenarios such as shopping cart;

2. Security

The cookie stores the information on the client. If encryption is not performed, some privacy information is undoubtedly exposed, and the security is poor. In general, sensitive information is encrypted and stored in the cookie, but it is easy to be stolen. Sessions only store information on the server. If they are stored in files or databases, they may also be stolen, but they may be much less likely than cookies.

Session hijacking is prominent in terms of session security. This is a security threat and will be described in more detail in the following sections. Generally, Session Security is higher than Cookie security;

3. Performance

The cookie is stored on the client, which consumes the client's I/O and memory, while the session is stored on the server, which consumes the server's resources. However, session puts more pressure on the server, while cookie disperses resource consumption. In this case, cookie is superior to session;

4. Timeliness

The cookie can be set to have a long period of memory on the client, while the session generally only has a short period of validity (timeout occurs when the user actively destroys the session or closes the browser );

5. Others

Cookie processing is not convenient during development. In addition, the number and size of cookies on the client are limited, while the size of the session is limited only by hardware. Therefore, the amount of data that can be stored is too large.

 

 

There are too many things to learn about session and cookie. Now, understanding is just a glimpse.

 

Online resources come from:

Http://www.cnblogs.com/shoru/archive/2010/02/19/1669395.html session

Http://www.cnblogs.com/fish-li/archive/2011/07/03/2096903.html details cookie

Application of http://www.cnblogs.com/langzi127/archive/2009/04/08/1431730.html cookie

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.