skillfully using ASP. NET Cookie

Source: Internet
Author: User

First, what is a cookie

A cookie is a small text message that has a text file on the client's hard disk that does not exceed 4KB in length.
Along with user requests and pages passing between the Web server and the browser
Each time a user accesses a site, the Web application can read the information contained in the cookie.

Second, the principle of work

Because HTTP is a stateless protocol, the server does not know the identity of the client from the network connection. What do we do? Give the client a pass, one per person, who must bring their own pass for whoever accesses it. This allows the server to confirm the identity of the client from the pass. That's how cookies work.
A cookie is actually a small piece of text information. The client requests the server and, if the server needs to log the user state, uses response to issue a cookie to the client browser. The client browser will save the cookie. When the browser requests the site again, the browser submits the requested URL along with the cookie to the server. The server checks the cookie to identify the user state. The server can also modify the contents of the cookie as needed.

Iii. properties and methods of the Cookie object
Property:
(1). Name: Gets or sets the names of the cookies
(2). Value: Gets or sets the value of the cookie
(3). Expires: Gets or sets the expiration time of the cookie
(4). Version: Gets or sets the versions of the cookie that conform to the HTTP maintenance state

Method:
(1). Add: Add cookie variable to save the specified cookie in the cookie collection
(2). Clear: Clears the variables in the cookie collection
(3). Get: The value of a cookie variable is obtained by a variable name or index
(4). Remove: Delete Cookie object by cookie variable name or index

Iv. Advantages and Disadvantages

Advantages:
The use of cookies can persist user information compared to session and application objects. Cookies are stored on the client, while sessions and application are stored on the server side, so cookies can be stored for long periods. The Web application can authenticate users by obtaining a cookie from the client.
ASP. NET contains two cookie collections, accessed through the HttpRequest cookie collection, which is not a subclass of the page class, so the usage differs from the session and application, as compared to the advantages of their cookie:
1. Can configure Expiration time
2. Simple: A cookie is a lightweight, text-based structure that includes simple key-value pairs
3. Data persistence: Because it is saved to the client
4. No server resources: Because the local client is stored

Disadvantages are as follows:
1. Size limit:
2. Uncertainties: Users may delete cookies or disable
3. Security risk: Can forge modification

V. What to pay attention to?
[1]. When you use a cookie to save request information for a client browser requesting a server page, the length of time you save depends on the expires attribute of the cookie object and can be set as needed. If the cookie expiration date is not set, they are only saved until the browser is closed. Setting the Expires property of a cookie object to DateTime.MaxValue indicates that the cookie will never expire.

[2]. The amount of data stored by a cookie is limited, and most browsers support a maximum capacity of 4096 bytes, so do not use cookies to store large amounts of data.

[3]. Not all browsers support cookies, and the data is stored in clear text on the client computer, so it is best not to use cookies to store sensitive unencrypted data.

[4]. There are two sets of cookies in asp: The Response object's cookie collection and the cookie collection of the request object, but the two have different roles, through which the cookie can be written to the client, through which the cookie stored on the client can be read.
Next, we'll talk about the practical application of cookies.

  • After the first logon, the login information is written to the cookie of the user's computer;
  • When logged in again, the cookie information in the user's computer is read out and displayed for the user to choose to use;
  • You can use the information in the read out cookie to log in directly to the website.
  • Action steps

    1, In VS Create a blank ASP. NET application, in Project Manager, add a Web form, use a 2 row 3-column table for layout, and after the layout ends, place 2 label controls on the left side of the layout table, set their Text property to user name and password, and add two Textbo to the layout table, respectively x control, a button control, and a CheckBox control, set the button control's Text property to log on, and the CheckBox control's Text property to remember user name and password.

    2, add an HTML page

        change the name to login.html

    3 by default, write event-handling code  

    <span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" >protected void Button1_Click (object sender, EventArgs e) {if (checkbox1.checked) {Response. cookies["ID"]. Expires = new DateTime (2016, 2, 24); Set the time to live response.cookies["PW" with a cookie with the key name ID.         Expires = new DateTime (2016, 2, 24); response.cookies["ID"]. Value = TextBox1.Text; Set the value of the cookie with the key name ID to the text box content response.cookies["PW"].       Value = TextBox2.Text;       } Response.Redirect ("login.html"); }</span> 

  • First, determine whether the cookie defined by the page is empty, and if it is not empty, read the contents of the cookie and place it in the TextBox1 and TextBox2 two text boxes, so that when the user logs on to the same page for the second time on their machine, click the login button directly. Skip the process of entering user IDs and passwords again
    <span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" > protected void Page_Load (object sender, EventArgs e)     {       if (request.cookies["ID"]! = null && Request. cookies["PW"] = null)       {         TextBox1.Text = request.cookies["ID"]. Value.tostring ();         TextBox2.Text = request.cookies["PW"]. Value.tostring ();//read out the value of the cookie with the key ID and display it in the text box TextBox2       }      

      

    • Save the user's personal interests, the designer can set the style of the website according to the user hobby recorded in the cookie;
    • Record the product information that the user buys when making online shopping;
    • Record the pop-up window is pop-up, some pages will be opened when the notification or advertising window, you can use the cookie record window is ejected, to see if the pop-up window has been ejected, if it has been popped, again open the page will not pop up the pop-up window.

skillfully using ASP. NET 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.