Is the ASP. NET Cookie object gross? (Simple example), asp. netcookie

Source: Internet
Author: User

Is the ASP. NET Cookie object gross? (Simple example), asp. netcookie

I remember that when I first came into contact with asp.net, I had a headache with several concepts, such as Request, Response, Session, and Cookie. There are also various searches in the search engine and various questions from colleagues, but the results are still very stable.

So what is the cookie? The following is my favorite Explanation Method (which is officially defined as "I don't understand my IQ ~)

The Cookie object is also called a cache object. It is used to save the Server Page requested by the client browser and store non-sensitive user information.

I didn't understand it in the past, but now it's actually awesome.

Let's use an example to understand this concept.

1. Create a user logon interface and use cookies to save logon information.

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 (Response) {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); // set the cookie validity period to 10 s cookie_password.Expires = dtNow. add (ts );}}

This example is very simple. The idea is to select the checkbox to remember the password, create a cookie to record the password content, and set the validity period. When you load the cookie next time, check whether the "password" cookie exists. If yes, check whether the cookie expires. If not, obtain the value saved in the cookie, in the corresponding text box.

The reason for setting the validity period to 10 s is to make the effect more obvious. As long as you constantly refresh the page, you will find that the password is still valid for 10 s. After 10 s, it will be automatically cleared. This is because the cookie expires.

2. One function to count the number of Logon pages of the current IP address. Interface

In fact, this example is quite interesting, and the interface is very simple, but there are more problems.

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            {                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 first obtain the local IP address, which ensures that a unique key is provided to the Cookie when the Cookie is added. When you refresh the page, determine whether a Cookie with the same name exists in all current cookies. If the cookie does not exist, create a new cookie. Of course, the key of the cookie is the IP address. Is the else part of Page_Load. If yes, add 1 to the original value. Note that you must modify the existing Cookie value.

At the beginning, I used the commented @ line of code, which is a normal idea. There is no problem with reading it, but it cannot be written in this way. It is loaded every time after the first loading, the obtained Request. cookies [ipAddress]. the Value is always 1. Therefore, you must use the set method of cookies to modify the existing cookie values.

In addition, you need to note that when you delete a cookie, you cannot use the Cookies. Remove or Cookies. Clear () method to achieve the desired effect. Add Expires to a negative value. Then update the Cookie and delete it. This will completely disappear. Otherwise it will appear again during the next loading. Why? I wrote a Request before. cookies. clear (), when the breakpoint is followed, all the cookies are indeed cleared, but when the cookie is loaded again, the breakpoint is set before the cookie is added, the previously deleted cookie appears again. Very strange ~~

If you want to understand what is going on, tell me what is going on.

Two simple small examples make you no longer feel so unfamiliar and afraid of cookies. Therefore, the concept is still effective, and it is the best practice ~


Cookie in aspnet

Expires is used to set the cookie expiration time.

Cookie. Expires = DateTime. Now;
The cookie expires when the current time exceeds the current time.

Cookie. Expires = DateTime. Now. AddDay (1 );
The expiration time is one day after the current time.

The unit can be minute, second, or day or month ....

Cookie problems in aspnet

If you write a Cookie by creating an instance of the HttpCookie object
1. Create an HttpCookie object and assign it a name.
2. assign values to the Cookie subitem and set all Cookie attributes.
3. Add the Cookie to the Cookies set. (This is required. This is the rule)

You create an HttpCookie object named cookie. This instance indicates a Cookie named tes.

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.