ASP. NET cookie concept, curd operation, principle, practical application

Source: Internet
Author: User

In the case of web development, a session is a conversation between your browser and the server, except that the call is done in a browser-based way.

In the case of conversational applications, a generic session is used to identify the user, for example, you can use session-level variables to record user-name passwords that are already entered by the current user, so that they do not have to be entered every time, and can be used to record other information related to the current call. Once you have closed the browsing
The session does not end, but when you reopen the browser, you cannot reuse the previous session, it will create a new session. The server automatically closes the session after a timeout based on the preset settings, or you can end the session manually.

I. Basic concepts of cookies

A cookie is a client-side technology that the server writes each user's data to a user's browser in the form of a cookie. When users use a browser to access Web resources on the server, they take their own data.

Knowledge of cookies also requires the following points.

1. A cookie is just a string and cannot be executed.

2, most browsers stipulate that the cookie size does not exceed 4K, each site can save more than 20 cookies, all sites save the total number of cookies not more than 300.

3, in addition to the cookie, there is almost no other way to write data on the client machine (even the cookie write operation is the browser). Of course, even cookies can be banned through browser security configuration.

Microsoft Internet Explorer Settings method: Tools > Internet Options > Privacy page Adjust slider or click "Advanced" to set it up.

4. When using cookies, you must be aware of their inherent security weaknesses. After all, cookies are stored on the client. Therefore, do not keep confidential information in the cookie, such as user name, password, credit card number, etc. Do not store content that should not be held by the user in a cookie, or that may be controlled by someone else who steals cookies.

5. cookie file storage address (ie browser view tools > Internet Options > General tab-Settings-view files):

Second, ASP. NET curd operation of cookies

The code is as follows:

         //three ways of writing cookies//Mode 1            varCookie =NewHttpCookie ("name","joye888");            RESPONSE.COOKIES.ADD (cookie); //Mode 2response.cookies["name1"]. Value ="joye8881"; response.cookies["name1"]. Expires =DateTime.MaxValue; //Mode 3            varAcookie =NewHttpCookie ("name2"); Acookie. Value="joye8882"; Acookie. Expires=DateTime.MaxValue;            RESPONSE.COOKIES.ADD (Acookie); //write a multi-valued cookie//Mode 1://response.cookies["UserInfo" ["Name"].            Value = "joye888"; //response.cookies["UserInfo"].            Expires = DateTime.MaxValue; //Mode 2:HttpCookie Cookie2 =NewHttpCookie ("UserInfo"); Cookie2. values["name"] ="joye888"; Cookie2. Expires= DateTime.Now.AddDays (1);            RESPONSE.COOKIES.ADD (COOKIE2); //before reading the value of a cookie, you should ensure that the cookie does exist. Otherwise, you will get an exception//Read Cookies            varHttpCookie = request.cookies["name1"]; if(HttpCookie! =NULL)            {                varName =Httpcookie.value; }            //read a multi-valued cookie            varHttpCookie1 = request.cookies["UserInfo"]; if(HttpCookie1! =NULL)            {                varname1 = httpcookie1["name"]; }            //Modify and delete cookies//The method of modification is the same as the creation method            varCookieedit =NewHttpCookie ("name","Joye888edit"); Cookieedit.expires= DateTime.Now.AddDays (-1);//set its validity period to a date in the past. This expired cookie is deleted when the browser checks the validity period of the cookie. Response.Cookies.Add (Cookieedit); //If you have a master station and a level two domain name station and the cookie is shared, add the following settingsCookies. Domain ="www.cnblog.com"; Cookies. Path="/";

Browser to view written Cookie,f12:

Third, the cookie operation principle diagram

Iv. precautions for use of cookies

Although the cookie is a simple and practical object, we should also pay attention to the principle of the cookie, size limitations and security, etc., can be summed up as the following points.

1, the physical location of the storage. In the client's cookie folder.

2. The type limit of storage. String.

3, the scope of the state use. The context of the current request context can be accessed to Cookie,cookie independent for each user.

4, the storage size limit. Each cookie does not exceed 4K data. No more than 20 cookies per website. The total amount of cookies on all websites is no more than 300.

5, life cycle. Each cookie has its own expiration time and expires after the expiration time.

6, security and performance. Stored on the client side, with poor security. Recommended for sensitive data storage after encryption.

7, advantages and disadvantages and precautions. You can easily associate websites and users, and save user settings for long periods of time.

V. Practical use of cookies

Login remember user name and password example

Page code:

<body> <form id="Form1"Method="Post"action="rembpage.aspx"> <div>Account Number:<input type="text"Name="UserName"/><br/>Password:<input type="Password"Name="Pass"/><br/>Remember me:<input type="checkbox"Value="REM"Name="Sele1"/><br/> <input type="Submit"Value="Login"/> </div> </form></body>

Implementation code:

if(request.cookies["UserName"] ==NULL&& request.cookies["PassWord"] ==NULL)//determine if there is a cookie, if present indicates the last time you selected remember me            {                if(request.form["UserName"] !=NULL&& request.form["Pass"] !=NULL) {String userName= request.form["UserName"]; String UserPassword= request.form["Pass"]; if(UserName = ="Admin"&& UserPassword = ="123")                    {                        if(request.form["Sele1"] !=NULL) {HttpCookie cookieusername=NewHttpCookie ("UserName", userName);//Create a cookie instance of your accountHttpCookie Cookiepassword =NewHttpCookie ("PassWord", UserPassword); Cookieusername.expires= DateTime.Now.AddDays (2);//set the expiration time of the account cookie, and the current time is pushed back two daysCookiepassword.expires =NewDateTime ( -,5, -);//set the expiration time for the password cookie, which expires May 27, 2012RESPONSE.COOKIES.ADD (Cookieusername);//Enter the created Cookieusername file into the browser sideResponse.Cookies.Add (Cookiepassword); Response.Redirect ("index.aspx");//Jump to the page you want                        }                        Else{Response.Redirect ("index.aspx");//Jump Even if you don't remember your password                        }                    }                }            }            Else{Response.Redirect ("index.aspx");//If you remember the password, the second login will go directly to the index.aspx page}

ASP. NET cookie concept, curd operation, principle, practical application

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.