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.

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/3F/03/wKioL1PIgVDiZ7M0AAAznAJrRow609.jpg "title=" Qq20140717165812.jpg "alt=" Wkiol1pigvdiz7m0aaaznajrrow609.jpg "/>

Background code:

        protected void page_load (object sender,  Eventargs e)         {             if  (request.cookies["password"] != null)              {                 if  (DateTime.Now.CompareTo (request.cookies["password"). Expires)  > 0)                  {                     textbox_password. text = request.cookies["Password"]. value;                }             }        }         Protected void button_login_click (object sender, eventargs e)          {            if  ( Checkbox_remember. Checked)             {                 httpcookie cookie_password =  new httpcookie ("password");                 cookie_password. Value = textbox_password. text;                 RESPONSE.COOKIES.ADD (Cookie_password);                 datetime dtnow = datetime.now;                 timespan ts = new timespan (0, 0, 0, 10);//This is to set the validity period of the cookie to 10s                 cookie_ 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

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/3F/03/wKioL1PIgWLAUzWjAAAh4AF19Fs979.jpg "title=" Qq20140717172847.jpg "alt=" Wkiol1pigwlauzwjaaah4af19fs979.jpg "/>

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

Background code:

        string ipaddress = string. Empty;        protected void page_load (Object sender,  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 = new httpcookie (ipAddress);                      Cookie_ip. value =  (Convert.ToInt32 (request.cookies[ipaddress). Value) ( + 1). ToString ();                     response.cookies.set (COOKIE_IP);                 }                 else                 {                    httpcookie cookie_ip =  new httpcookie (ipAddress);                         cookie_ip. value =  "1";                     response.cookies.add (COOKIE_IP);                     DateTime dtNow =  datetime.now;                     timespan ts = new timespan (0, 0, 0, 20);                      cookie_ip. Expires = dtnow.add (TS);                 }             }        }         protected void button_statistics_click (object  Sender, eventargs e)         {             if  (request.cookies[ipaddress] != null)              {                 textbox_count. Text = request.cookies[ipaddress]. value;            }             else             {  &nBsp;             textbox_count. text =  "0";            }         }        protected void  Button_clear_click (object sender, eventargs e)         {             HttpCookie cookie_ip =  New httpcookie (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 ~


Sina Weibo:http://weibo.com/zhouhongyu1989 welcome Onlookers ~!

This article is from the "Give Me a Gener cigarette" blog, please be sure to keep this source http://zhouhongyu1989.blog.51cto.com/2931598/1439810

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.