Asp. NET Chapter session and Cookie

Source: Internet
Author: User
Tags sessions

Session:

Session is the meaning of "conversation", however, because the HTTP protocol is stateless, every time the client requests the server side, the server will be "brand new" page to the client, which in the static HTML page has no effect, but in the dynamic page, need to interact with the user, To maintain contact with the client user, something needs to be maintained, while the session is capable of having a "keep-alive, conversational" capability.

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

Three steps to create a session on the server side (online reference):

1. Generate a Globally unique identifier (SESSIONID);

2. Open up data storage space. It is common to create the appropriate data structure in memory, but in this case, once the system loses power, all session data will be lost, and if it is an e-commerce website, the accident will have serious consequences. However, it can also be written in a file or even stored in a database, although this will increase I/o overhead, but the session can achieve some degree of persistence, and more conducive to the sharing session;

3. Character the global unique label of the session to the client.

The key to the problem is how the server sends the session's unique identity. By contacting the HTTP protocol, the data can be placed in the request line, header domain, or body, and there are generally two common ways to do this: cookies and URL rewriting.

1. The cookie (SessionID will be stored in the cookie, and the expiration time is 0, which is the effective time of the browser process, if the browser is closed, then the session will expire, the principle is this)

The reader should have thought that, yes, the server can send the session identifier to the client as long as the Set-cookie header is set, and each subsequent request from the client will be given this identifier, since the cookie can set the expiration time, Therefore, the cookie that normally contains session information is set to expire at 0, which means the browser process is valid for the time. As for the browser how to deal with this 0, each browser has its own scheme, but the difference is not too large (generally in the new browser window);

2. URL rewrite (usually online URL address on the sessionid=xxxx word)

The so-called URL rewrite, as the name implies is rewrite URL. Imagine, before returning the page of a user request, all the URLs in the page are followed by a get parameter with the session identifier (or in the path info section, etc.) so that the user receives the response, regardless of which link or submission form is clicked, will take the session identifier again, thus realizing the conversation's retention. Readers may find this to be cumbersome, indeed, but if the client disables cookies, URL rewriting will be preferred.

Basic usage of session in ASP.

When defining: session["ddd"]=XXXX;

When in use: session["DDD"]

If you need to save the object of the class, the usage is the same as ViewState:

Send side:

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");

Receiving end:

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: Timeout and manual destruction):

The default time setting for an ASP. NET session is 20 minutes, which means the server will automatically discard session information after more than 20 minutes.

Session Hijack (online reference):

Session Hijack is a serious security threat and a widespread threat, and in session technology, the client and server maintain sessions by transmitting the session identifier, but this identifier can easily be sniffed and exploited by others. This belongs to a kind of middle man attack.

Cookies

The biggest benefit of cookies is the service "Remember Me".

Cookies are stored on the client, and if the user disables the cookie, there may be some problems, so be careful when designing (judging if the cookie is null)

The reason for the need for cookies is the same as the need for a session, because the HTTP protocol is stateless, each time it is a new page, will not save any information, and the cookie will be saved on the client computer, then when needed, you can use the backend server-side call, You can also use the client to make the call.

A cookie is just a piece of text, so it can only hold strings. and the browser has a size limit on it and it will be sent to the server with each request, so it should be guaranteed not to be too large. The content of the cookie is also stored in plaintext, and some browsers provide an interface modification, so it is not appropriate to store important or privacy-related content. (Online reference)

Limitations of Cookies:

Most browsers support a maximum of 4096 bytes of cookies. Because this limits the size of cookies, it is best to use cookies to store small amounts of data, or to store identifiers such as user IDs. The user ID can then be used to identify the user and to read user information from a database or other data source. The browser also restricts the number of cookies that the site can store on the user's computer. Most browsers allow only 20 cookies per site, and if you try to store more cookies, the oldest cookie is discarded. Some browsers also impose an absolute limit on the total number of cookies they will accept from all sites, typically 300.

Attributes in a cookie: (online reference)

Name: Each cookie is represented by a unique name that can contain letters, numbers, and underscores. The name of the cookie is not case-sensitive, so MyCookie and MyCookie are the same. But considering that the server-side language may be case sensitive, it is recommended to define and use case-sensitive.

Value: The string value that is stored in the cookie. This value must be encoded with encodeuricomponent () before it is stored to avoid losing data or consuming cookies. Note: The number of bytes added to the cookie name and value cannot exceed 4095 bytes, or 4KB.

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

Another security feature of Path:cookie that restricts access to specific directories on the Web server. That is, control which accesses can trigger the send. For example, the requested address is the URL above, and if Path=/foo, the cookie will be sent, but if path is otherwise, the cookie will be ignored.

The expiration time of the Expires:cookie.

Secure: A True/false value that indicates whether a cookie can be accessed only from a secure Web site (a website that uses SSL and HTTPS protocols). If this value is set to True

Basic Steps for Cookies: (online reference)

Steps for the browser to answer cookies in the header of the Web server:

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

B. Parse the components of these cookies (name, value, path, etc.).

C. Determine if the host is allowed to set these cookies. If allowed, these cookies are stored locally.

Steps for the browser to filter all cookies in the Web server request header:

A. Depending on the URL of the request and the properties of the local store cookie, the cookie can be sent to the Web server.

B. For multiple cookies, determine the order in which they are sent.
C. Add the cookie that needs to be sent to the request HTTP header.

Basic usage of cookies in asp:

Send side:

HttpCookie cookie = new HttpCookie ("UserInfo");

cookie["name"] = name. Text;

Cookie["age") = age. Text;

cookie["sex"] = sex. Text;

cookie["language"] = language. Text;

Cookies. Expires = DateTime.MaxValue;

RESPONSE.COOKIES.ADD (cookie);

Response.Redirect ("cookie2.aspx");

Receiving end:

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 conditional judgment on the receiving end, which avoids the error if cookies are disabled, and determines whether the cookie exists.

Use of cookies:

Prevention of repeated online voting;
Automatic Login via Cookies
Single-sign-on, SSO is one of the most popular solutions for enterprise business integration at the moment. Simply put, in multiple applications, users only have to log in once to gain access to all applications that trust each other. It includes a mechanism that can map this major login to other apps for the same user's login.

Session and Cookie Comparison: (online reference)

1. Application Scenarios

A typical application scenario for a cookie is the Remember Me service, where the user's account information is stored on the client in the form of a cookie, and when the user requests a matching URL again, the account information is sent to the server and the corresponding program completes the automatic login function. Of course, you can also save some client information, such as page layout, search history, and so on.

A typical scenario for a session is when a user logs in to a Web site, puts his or her login information into session, and then queries each subsequent request for the appropriate login information to ensure that the user is legitimate. Of course, there are shopping carts and other classic scenes;

2. Security

Cookies keep information on the client side, and without encryption, there is no doubt that some privacy information is compromised, and in general the sensitive information is encrypted and stored in a cookie, but it is easily stolen. The session will only store information on the server side, and if stored in a file or database, there is also the possibility of being stolen, but the likelihood is much smaller than the cookie.

Session security is more prominent in the context of the issue of the existence of a conversation hijacking, which is a security threat, which is described in more detail below. Generally speaking, the session security is higher than the cookie;

3. Performance

The cookie is stored on the client, consumes the client's I/O and memory, and the session is stored on the server, consuming resources on the server side. However, the stress of the session on the server is relatively concentrated, and the cookie is very good to disperse the resource consumption, in this case, the cookie is better than the session;

4. Timeliness

Cookies can be set for a longer period of time to exist in the client, and the session is generally only a relatively short period of validity (the user actively destroy the session or close the browser after the timeout);

5. Other

The processing of cookies is not convenient for the session in development. And there is a limit on the number and size of cookies in the client, and the size of the session is limited only by hardware, and the data that can be stored is undoubtedly much larger.

There's too much to learn about session and Cookie, and now it's just fur.

Online resources from:

Http://www.cnblogs.com/shoru/archive/2010/02/19/1669395.html Big Talk Session

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

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

Asp. NET Chapter session and Cookie

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.