What is an ASP. NET Cookie object? (Simple small example)

Source: Internet
Author: User

Remember that when I first approached ASP, I got a headache with several concepts, such as request,response,session and cookies. Then also a variety of search engines, all kinds of asking colleagues, but the result is that they are still very confused rhythm.

Is that cookie really hairy? Here is my least favorite way of explaining (the official definition of it should be called, I am not able to understand the IQ)

A cookie object is also called a cache object, which is used to hold the server page of a client browser request, and it can store non-sensitive user information.

I didn't understand it before, and now I'm really ignorant of it.

Or an example of how this concept can be figured out.

1, do a user login interface, using cookies to save the login information function.

Background code:

protected voidPage_Load (Objectsender, EventArgs e) {if(request.cookies["Password"] !=NULL)            {if(DateTime.Now.CompareTo (request.cookies["Password"]. Expires) > 0) {textbox_password. Text = request.cookies["Password"].                Value; }            }        }protected voidButton_login_click (Objectsender, EventArgs e) {if(Checkbox_remember. Checked) {HttpCookie Cookie_password =NewHttpCookie ("Password"); Cookie_password. Value = Textbox_password.                Text;                RESPONSE.COOKIES.ADD (Cookie_password);                DateTime Dtnow = DateTime.Now; TimeSpan ts =NewTimeSpan (0, 0, 0, 10);//This is to set the validity period of the cookie to 10sCookie_password.            Expires = Dtnow.add (ts); }         }

This example is simple, the idea is to choose to remember the Password checkbox, create a cookie to record the contents of the password, and set the validity period. When the next load, determine whether there is this "password" cookie, some words to determine if the cookie expires, if not expired, the value of the cookie stored in the corresponding text box is removed.

The reason for setting the validity period to 10s here is to make the results visible to everyone. As long as you continue to refresh the page, you will find that before 10s, the password part still has a value, over the 10s, automatically emptied. This is because the cookie expires.

2, a statistics of the current number of IP login page function. Interface

In fact, this example is more interesting, the interface is very simple, but the problem is slightly more.

Background code:

        stringIpAddress =string. Empty;protected voidPage_Load (Objectsender, EventArgs e) {ipAddress = Dns.gethostbyname (Server.MachineName.ToString ()). Addresslist[0]. ToString ();if(! IsPostBack) {if(Request.Cookies.AllKeys.Contains (ipAddress)) {//request.cookies[ipaddress]. Value = (Convert.ToInt32 (request.cookies[ipaddress]. Value) + 1). ToString (); @@@HttpCookie cookie_ip =NewHttpCookie (ipAddress); Cookie_ip. Value = (Convert.ToInt32 (request.cookies[ipaddress]. Value) + 1).                    ToString ();                Response.Cookies.Set (COOKIE_IP); }Else{HttpCookie Cookie_ip =NewHttpCookie (ipAddress); Cookie_ip. Value ="1";                    RESPONSE.COOKIES.ADD (COOKIE_IP);                    DateTime Dtnow = DateTime.Now; TimeSpan ts =NewTimeSpan (0, 0, 0, 20); Cookie_ip.                Expires = Dtnow.add (ts); }            }        }protected voidButton_statistics_click (Objectsender, EventArgs e) {if(request.cookies[ipaddress]! =NULL) {Textbox_count. Text = request.cookies[ipaddress].            Value; }Else{Textbox_count. Text ="0"; }        }protected voidButton_clear_click (Objectsender, EventArgs e) {HttpCookie cookie_ip =NewHttpCookie (ipAddress); Cookie_ip.            Expires = DateTime.Now.AddDays (-1);            Response.Cookies.Set (COOKIE_IP);            Request.Cookies.Remove (ipAddress);        Request.Cookies.Clear (); }

The idea of this small example is to get the local IP address first, which ensures that when a cookie is added, a unique key is given to the cookie. When refreshing the page, determine if there is a cookie with the same name in all of the current cookies. If it does not exist, create a new cookie, of course, the KEY=IP address of this cookie. is part of the else in Page_Load. If so, add 1 based on the original value. It is important to note that you are modifying the existing cookie value.

At the beginning of the time I used is commented out @@@ 这 line of code, is the normal thinking, there is no problem to look at it, but this can not be written, the first time after loading each load, take the request.cookies[ipaddress]. Value is always 1. Therefore, it is necessary to use the set method of cookies to modify the existing cookie value.

There is also a place to note, that is, when deleting cookies, if the direct use of the Cookies.remove or Cookies.clear () method can not achieve the desired effect. Need to cooperate with expires, give a negative value. Then go to update the cookie and delete it so that the cookie disappears completely. otherwise at the next loading time will appear, this really do not know why? I wrote a Request.Cookies.Clear before (), when the interrupt point followed, all the cookies are actually emptied, but when loading again, the breakpoint before adding the cookie, you will find that the previously deleted cookie appears again. It's strange.

Hope to understand the friends tell me what's going on ha.

Two simple little examples to make yourself feel so unfamiliar and afraid of cookies. So light to see the concept or effect generally, hands is the King Ah ~

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.