Skillful use of asp.net cookie_ practical skills

Source: Internet
Author: User

Let's take a look at the cookie learning map and see what you learn.

What is a cookie?

A cookie is a small piece of text information that exists on a client hard disk with a text file that is no longer than 4KB.
Accompanied by user requests and pages passed between the Web server and the browser
Each time a user accesses a site, the Web application can read the information that the cookie contains.

Second, the principle of work

Because HTTP is a stateless protocol, the server alone does not know the identity of the customer from the network connection. What do we do? Give the client a pass bar, each person, no matter who visit must carry their own pass. This will enable the server to confirm the identity of the customer from the pass. That's how cookies work.
A cookie is actually a small piece of textual information. The client requests the server, and if the server needs to log that user state, use response to issue a cookie to the client browser. The client browser will save cookies. 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 status. The server can also modify the contents of the cookie as needed.

Properties and methods of cookie objects
Properties:

(1). Name: Gets or sets the names of cookies
(2). Value: Gets or sets the value of the cookie
(3). Expires: Gets or sets the expiration time of a cookie
(4). Version: Gets or sets the HTTP maintenance-compliant versions of cookies

Method:
(1). Add: Add cookie variable, save the specified cookie to the Cookies collection
(2). Clear: Clears the variables in the cookie collection
(3). Get: Gets the value of a cookie variable by variable name or index
(4). Remove: Deletes a cookie object from a cookie variable name or index

Iv. Advantages and Disadvantages

Advantages:
use cookies to persist user information, compared to session and application objects. Cookies are stored on the client, and session and application are stored on the server side, so cookies can be saved for a long time. A Web application can authenticate users by obtaining a cookie from the client.
The asp.net contains a collection of two cookies, accessed through a HttpRequest cookie collection, and is not a subclass of the page class, so using the method differs from session and application, compared to the advantages of their cookies:
1. Can configure Expiration time
2. Simple: Cookies are 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 stored on the local client

disadvantages are as follows:
1. Size limit:
2. Uncertainty: Possible users to delete cookies or disable
3. Security risk: May forge the modification

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

[2]. Cookies store a limited amount of data, and most browsers support a maximum capacity of 4096 bytes, so do not use cookies to hold 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 the ASP.net, namely: The Response object's cookie collection and the Request object's cookies collection, but the function is different, through the former can write the cookie to the client, through the latter can read the cookie stored in the client.
Next, we'll talk about the actual application of cookies.

First set up the interface as shown in the diagram, through which you can log on to a Web site, specific requirements are as follows:

    • After the first logon, write the login information to the user's computer cookie;
    • When you log on again, read and display the cookie information in the user's computer, in case the user chooses to use it;
    • You can use the information in the read cookie to login directly to the site.

Operation 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, place 2 label controls on the left side of the layout table, set their Text property to the user name and password, and add two Textbo to the layout table x control, a button control, and a CheckBox control, set the button control's Text property to log on, and set the CheckBox control's Text property to remember user name and password.

2. Add an HTML page

Change the name to login.html by default

3. 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 lifetime 
        response.cookies["PW" with a cookie with the key name ID. Expires = new DateTime (2016, 2); 
        response.cookies["ID"]. Value = TextBox1.Text; Set the value of the cookie with the ID of the key to the text box content 
        response.cookies["PW"]. Value = TextBox2.Text; 
      } 
      Response.Redirect ("login.html");  
 
    } </span>

First, determine whether the cookie for the page definition is empty, and if not NULL, read the contents of the cookie and place it in the TextBox1 and TextBox2 two text boxes so that the user clicks the login button the second time he or she logs on to the same page on his or her own machine. The process of entering the user ID and password again is omitted

<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 the value of the cookie with the ID of the key, and display it in the text box TextBox2 
      } 
 
    

When the page is loaded again, it appears as shown in the following figure.

It simply shows a few of the more common features (keep the user's personal information, such as name, password, etc., to help users quickly log on to the web), there are many unknown features let us explore
For example:

    • Save the user's personal hobby, the designer can set the website style according to the user hobby which the cookie records;
    • When making online shopping, record the product information that the user buys;
    • Record pop-up window is ejected, some of the pages will be open pop-up notification or advertising window, you can use cookies to record the pop-up window, to see if the pop-up window has been ejected, if the pop-up, open the page again will no longer pop-up the pop-up window.

By knocking This example let me more in-depth understanding of how cookies are used, before seeing this kind of similar articles are hiding not to see, it is certainly rare, but I try to know, in fact, is not difficult, so learn must not be afraid of difficulties.

The above is the entire content of this article, I hope to help you learn, we common progress!

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.