Brief introduction and use of Asp.net cookies

Source: Internet
Author: User
What is Cookie?

Cookie, which is sometimes used in the form of cookies, refers to the data stored on the user's local terminal for some websites to identify users and perform session tracking. Usually encrypted. Therefore, when you view the cookies saved by your browser to your local computer, these files are usually named in the format of user @ domain. The user is your local user name, domain is the domain name of the accessed website.

For example, view the csdn blog's local cookies:

File:

Content:

 

Because cookies are encrypted, all the information is ciphertext, and only a small amount of content can be understood. For example, in blog.csdn.net, we can guess that the content of this file is definitely related to the csdn personal blog, but the specific content is hard to understand because it is encrypted, encryption also ensures the security of information leakage.

To put it bluntly, when a cookie is used to access a website, the server saves the visitor's personal information in the form of a text document to the user's local computer, so that the user can directly read the personal information when accessing the website again. This technology is called Cookie. Once
If the cookie is saved on a computer, only the website that creates the cookie can read it.

 

What is the function of cookie?

One of the purposes of cookie is to store the user's password and ID on a specific website. A typical application is to determine whether a registered user has logged on to the website, and the user may be prompted to determine whether to keep the user information when entering the website for simplified login procedures. These are the functions of cookies. Another important application scenario is "Shopping Cart. Users may select different products on different pages of the same website within a period of time. These information will be written into ookies to extract information at the final payment. Companies use cookies
The general functions include: Online Ordering System, website personalization, and website tracking.


Cookie Lifecycle

Cookie can maintain the login information to the user's next session with the server. In other words, when accessing the same website next time, the user will find that the user has logged on without having to enter the user name and password (of course, users cannot delete cookies manually ). Some cookies are deleted when the user exits the session, which can effectively protect personal privacy.

When a cookie is generated, an expire value is specified. This is the cookie life cycle. During this period, the cookie is valid and will be cleared if it exceeds the cycle. Some pages set the cookie lifecycle to "0" or a negative value, so that when the browser is closed, the cookie will be cleared immediately without recording user information, making it safer.

When a website is designed to program cookies, if the content of the cookie with no expire value is temporarily stored in the memory, the information will be deleted after the browser is closed; after setting the expire value, the cookie is saved as text to the local host. The client sends the cookie to the server every time a browser is opened to access the website until the configured cookie expires, the browser clears the information.


Cookie Programming

Create cookie

Method 1:

Response.Cookies["username"].value="mike";Response.Cookies["username"].Expires=DateTime.MaxValue; 

Method 2:

HttpCookie acookie = new HttpCookie("username");acookie.Value="mike";acookie.Expires=DateTime.MaxValue; Response.Cookies.Add(acookie);

Create multi-value cookie

Method 1:

Response. cookies ["login"] ["username"]. value = "Mike"; response. cookies ["login"] ["password"]. value = "123456"; response. cookies ["login"]. expires = datetime. maxvalue; // The maximum validity period.

Method 2:

Httpcookie cookie = new httpcookie ("login"); cookie. values ["username"] = "Mike"; cookie. values ["password"] = "123456"; cookie. expires = system. datetime. now. adddays (1); // set the expiration time to 1 day response. cookies. add (cookie );

Cookie reading

Stringstr = request. Cookies ("username"). value; cookie multi-value read if (request. Cookies ["login"]! = NULL) {string name = request. Cookies ["login"] ["username"]; string Password = request. Cookies ["login"] ["password"];}

Delete cookie

Set the expiration time through expires, as shown in figure

cookie.Expires=DateTime.Now.AddDays(-30);

Cookie records the instance of the user name and password

. Aspx

<% @ Page Language = "C #" autoeventwireup = "true" codebehind = "login. aspx. cs" inherits = "testcookie. login" %> <! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <HTML xmlns = "http://www.w3.org/1999/xhtml"> 

. Aspx. CS

Using system; using system. collections. generic; using system. LINQ; using system. web; using system. web. ui; using system. web. UI. webcontrols; namespace testcookie {public partial class login: system. web. UI. page {protected void page_load (Object sender, eventargs e) {// The initial loading page determines whether a cookie exists. If yes, the user name and password in the cookie are read if (request. cookies ["login"]! = NULL) {string username = request. cookies ["login"] ["username"]; string Password = request. cookies ["login"] ["password"]; response. write (username); txtusername. TEXT = username; txtpassword. TEXT = PASSWORD ;}} protected void btnlogin_click (Object sender, eventargs e) {// Save the username and password httpcookie cookie when logging on for the first time cookie = new httpcookie ("login "); // create a cookie. values ["username"] = txtusername. text; // Save the cookie for the user name. values ["password"] = txtpassword. text; // Save the password cookie. expires = datetime. today. adddays (1); // set the expiration time. If this value is not set, if the cookie validity period is the session validity period, the browser will be disabled and the cookie will disappear. cookies. add (cookie); // response. write (cookie. values ["username"] + Cookie. values ["password"]); // response. write (request. cookies ["login"] ["username"] + request. cookies ["login"] ["username"]) ;}}

During the test, we used IE, 360, and Google browsers respectively. However, we found that the user name and password in IE cannot be read in other browsers, and other browsers cannot. This is because multiple browsers are installed on a computer, and each browser stores cookies in its own space. Because cookies can not only confirm users, but also contain information about computers and browsers, a user can obtain different cookie information when logging on through different browsers or using different computers, on the other hand, for multiple user groups that use the same browser on the same computer, cookies do not differentiate their identities unless they log on with different user names. Therefore, logging on to the website with different browsers will record different user information and access information.

Summary

In B/S development, cookie is a very common and important knowledge. We should not only learn to read and write cookies, but also have a comprehensive and systematic understanding of the purpose and lifecycle of cookies, this helps us better utilize and use cookies for programming. Of course, when Cookie is mentioned, the most important issue is security. Although data is encrypted in cookies, the encrypted information is intercepted by some ulterior motives on the Internet, he can't understand it either, because he only sees meaningless letters and numbers. However, the problem is that the person who intercepts cookies does not need to know the meaning of these strings. They only need to submit others' cookies to the server and can pass the verification, they can pretend to be victims and log on to the website. This method is called Cookie spoofing. Therefore, you need to have a deep understanding of and explore cookie knowledge.

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.