Asp. NET in the use of cookies _ Basic application

Source: Internet
Author: User
Tags allkeys datetime

Cookies provide a useful way for a WEB application to save user-related information. For example, when a user accesses a site, a Cookie can be used to save user preferences or other information so that the application can retrieve previously saved information the next time the user visits the site.

Technically, cookies are small pieces of data stored on the client (if you are installing XP, you can look at the < install Windows >:\documents and settings\< username >\cookies folder). When a user visits a Web site, the site gives the user a cookie containing the expiration time, and the browser receives the cookie and stores it under the client's folder. Each time the user visits the Site page, the browser will find out if there is a cookie associated with the current Web site in the local cookie folder based on the URL of the site, and if so, send it to the server along with the page request.

One, the knowledge of cookies also need to know the following points.

· The cookie is just a string and cannot be executed.
• Most browsers specify a cookie size of not more than 4K, each site can save more than 20 cookies, all sites save the total number of cookies not more than 300.
• In addition to cookies, there are few other ways to write data on a client machine (even a cookie's write operation is a browser). Of course, even cookies can be banned by browser security configuration. If you use IE browser, you can look at the "tools" → "Internet" option → "privacy" page. Most Web sites now use cookies to hold some data (such as your ID) so that you can "continue" the previous configuration the next time you visit the site, so I suggest that you do not turn cookies off easily.

When using cookies, you must be aware of their inherent security vulnerabilities. Cookies are stored on the client, after all. Therefore, do not store confidential information in cookies, such as user name, password, credit card number, and so on. Do not store content that should not be available to the user in a cookie, nor save content that may be controlled by someone else who steals cookies.

Second, the use of cookies

Next, we'll discuss how to save, read, delete, and modify cookies. First, add 4 buttons on the page to complete these 4 operations.

Copy Code code as follows:

<asp:button id= "Btn_savecookie" runat= "Server" onclick= "Btn_savecookie_click" text= "Save Cookies"/>
<asp:button id= "Btn_readcookie" runat= "server" text= "read cookies" onclick= "Btn_readcookie_click"/>
<asp:button id= "Btn_modifycookie" runat= "Server" onclick= "Btn_modifycookie_click" text= "Modify Cookie"/>
<asp:button id= "Btn_delcookie" runat= "server" text= "Delete Cookie" onclick= "Btn_delcookie_click"/>

The way to save cookies is as follows.

Copy Code code as follows:

protected void Btn_savecookie_click (object sender, EventArgs e)
{
HttpCookie Singlevaluecookie = new HttpCookie ("Test1", "Single value Cookie");
Singlevaluecookie.expires = DateTime.Now.AddDays (1);
RESPONSE.COOKIES.ADD (Singlevaluecookie);
HttpCookie Multivaluecookie = new HttpCookie ("Test2");
MULTIVALUECOOKIE.VALUES.ADD ("Key1", "value1");
MULTIVALUECOOKIE.VALUES.ADD ("Key2", "value2");
Multivaluecookie.expires = DateTime.Now.AddDays (1);
RESPONSE.COOKIES.ADD (Multivaluecookie);
}

As we can see, a cookie allows a single value to be saved and can hold multiple values. The HttpCookie type represents a Cookie,expires property used to modify the expiration time of a cookie. For a single value cookie, you can either specify a value directly in the constructor or specify a value using the Value property. For multivalued cookies, you can use the Add method of the Values property to add subkeys and values, or you can use the index of the values property to set subkeys and values directly. The above code is equivalent to the following code.

Copy Code code as follows:

protected void Btn_savecookie_click (object sender, EventArgs e)
{
HttpCookie Singlevaluecookie = new HttpCookie ("Test1");
Singlevaluecookie.value = "Single value cookie";
Singlevaluecookie.expires = DateTime.Now.AddDays (1);
RESPONSE.COOKIES.ADD (Singlevaluecookie);
HttpCookie Multivaluecookie = new HttpCookie ("Test2");
multivaluecookie.values["Key1"] = "value1";
multivaluecookie.values["Key2"] = "value2";
Multivaluecookie.expires = DateTime.Now.AddDays (1);
RESPONSE.COOKIES.ADD (Multivaluecookie);
}

After adding the value, be sure to use the response object to return the cookie back to the browser. Our servers do not write cookies directly on the client machine, but the browser does the job, and the user can also set whether the browser is allowed to read and write cookies.

The following is an operation to read a cookie.

Copy Code code as follows:

protected void Btn_readcookie_click (object sender, EventArgs e)
{
HttpCookie Singlevaluecookie = request.cookies["Test1"];
if (Singlevaluecookie!= null)
{
Response.Write (String. Format ("key:{0} Value:{1} expires:{2}<br/>", "test1", Singlevaluecookie.value, Singlevaluecookie.expires));
}

HttpCookie Multivaluecookie = request.cookies["Test2"];
if (multivaluecookie!= null)
{
Response.Write (String. Format ("key:{0} value:{1}<br/>", "Test2", Multivaluecookie.value));
foreach (String subkey in MultiValueCookie.Values.AllKeys)
{
Response.Write (String. Format ("subkey:{0} Value:{1} expires:{2}<br/>", subkey, Multivaluecookie.values[subkey], Multivaluecookie.expires));
}
}
}

For multivalued cookies, we get all the subkey keys by traversing the string array returned by the AllKeys property, thus obtaining the value of the subkey. Note that before you access the cookie, you need to check to see if the cookie exists. Open the page, click the Save Cookie button, and then click the Read Cookie button to get the following output:

Key:test1 Value: Single value cookie Expires:0001-1-1 0:00:00
Key:test2 value:key1=value1&key2=value2
Subkey:key1 value:value1 expires:0001-1-1 0:00:00
Subkey:key2 value:value2 expires:0001-1-1 0:00:00

Here are the following points.

• We have found that the expiration time for all cookies is not displayed properly. This is because the cookie that the browser returns to the server does not contain an expiration time, and the cookie that the server returns to the browser contains the expiration time. The expiration time is only meaningful to the client browser and has little meaning for the server.

• Directly read the value of a multivalued cookie, it will display all the subkeys and subkeys using the Key=value method, and the multiple child keys use the "&" connection (similar to the URL).

Here is the action to delete the cookie.

Copy Code code as follows:

protected void Btn_delcookie_click (object sender, EventArgs e)
{
HttpCookie Singlevaluecookie = request.cookies["Test1"];
Singlevaluecookie.expires = Datetime.minvalue;
RESPONSE.COOKIES.ADD (Singlevaluecookie);
}

If you want to delete all cookies, you can traverse the deletion.

Copy Code code as follows:

protected void Btn_delcookie_click (object sender, EventArgs e)
{
foreach (string key in Request.Cookies.AllKeys)
{
HttpCookie cookie = Request.cookies[key];
Cookie. Expires = Datetime.minvalue;
RESPONSE.COOKIES.ADD (cookie);
}
}

We always remember that the server cannot delete cookies directly, and the operation to delete cookies is in the browser. The deletion, in fact, is to set its expiration time to the past time, so that the cookie expires. Therefore, there are three steps for a delete operation.

1. Gets the cookie from the request object.
2. Set the expiration time of the cookie to the past time.
3. Re-write the cookie back into the response.
4. The operation of modifying cookies is also very simple.

Copy Code code as follows:

protected void Btn_modifycookie_click (object sender, EventArgs e)
{
HttpCookie Singlevaluecookie = request.cookies["Test1"];
Singlevaluecookie.value = "Modified single value Cookie";
RESPONSE.COOKIES.ADD (Singlevaluecookie);
}

Third, the cookie uses the extension

(1) Writing cookies

Copy Code code as follows:

Mode 1:
response.cookies["username"].value= "Mike";
response.cookies["username"]. Expires=datetime.maxvalue;

Mode 2:
HttpCookie acookie = new HttpCookie ("last");
Acookie. Value= "a";
Acookie.. Expires=datetime.maxvalue;
RESPONSE.COOKIES.ADD (Acookie);

The writing of multi-value cookies

Copy Code code as follows:

Mode 1:
response.cookies["Userinfo1" ["Name"].value= "Mike";
response.cookies["Userinfo1" ["Last"].value= "a";
response.cookies["Userinfo1"]. Expires=datetime.maxvalue;

Mode 2:
HttpCookie cookie = new HttpCookie ("Userinfo1");
Cookie. values["Name"]= "Mike";
Cookie. values["Last"]= "a";
Cookie. Expires=datetime.maxvalue;
Cookie. Expires = System.DateTime.Now.AddDays (1);/Set expiration 1 days
RESPONSE.COOKIES.ADD (cookie);

(2) Read cookies
Internet Explorer saves the site's cookies in a file with a filename format of <user>@<domain>.txt, where <user> is your account name.
Note: You should ensure that the cookie does exist before you get the value of the cookie. Otherwise, you will get an exception

Copy Code code as follows:

If (request.cookies["UserName"]!=null)
{
String str = request.cookies ("UserName"). Value;
}

Read multi-valued cookies
If (request.cookies["UserInfo1"]!=null)
{
String name=request.cookies["UserInfo1" ["Name"];
String last=request.cookies["UserInfo1" ["Last"];
}

Read Cookie Collection
for (int i = 0; I<request.cookies.count i++)
{
HttpCookie cookies = request.cookies;
Response.Write ("Name=" +cookies). Mame+ "<br/>");
if (cookies). HasKeys)//whether there are subkeys
{
System.Collections.Specialized.NameValueCollection Namecoll
= Acookie.values;
for (int j=0;j<namecoll.count;j++)
{
Response.Write ("Subkey name =" + Namecoll.allkey[j] + "<br/>");
Response.Write ("Subkey value =" + Namecoll[j] + "<br/>");
}
}
Else
{
Response.Write ("value=" +cookies). Value+ "<br/>");
}
}

When you run this code, you see a cookie,asp named "Asp.net_sessionid." NET uses this Cookie to save a unique identifier for your session.

(3) Delete cookies
Set its validity period to a date in the past. When the browser checks the validity of a cookie, it deletes the expired cookie.

Copy Code code as follows:

HttpCookie cookie = new HttpCookie ("Userinfo1");
Cookie. Expires=datetime.now.adddays (-30);
RESPONSE.COOKIES.ADD (cookie);

(4) Modify cookies

Copy Code code as follows:

response.cookies["Info" ["user"] = "2";
response.cookies["Info"].        Expires = DateTime.Now.AddDays (1); Delete a property under a cookie
HttpCookie acookie=request.cookies["Info"];
Acookie. Values.remove ("userid");
Acookie. Expires = DateTime.Now.AddDays (1);
RESPONSE.COOKIES.ADD (Acookie); Delete all cookies, that is, set the expiration time for now.
int limit=request.cookies.count-1;
for (int i=0;i<limit;i++)
{
Acookie = Request.Cookies (i)
Acookie. Expires = DateTime.Now.AddDays (-1)
RESPONSE.COOKIES.ADD (Acookie)
}

-------------

If you have a master station and a level two domain name station and cookies to share, you need to add the following settings

Copy Code code as follows:

Cookie. Domain = ". primary domain Name";
Cookie. Path = "/";

Four, Cookie Summary

Cookies are a simple and useful object, but we should also pay attention to the working principle of cookies, size limits and security, can be summed up in the following points.

• The physical location of the storage. Client's Cookies folder.
• Type restrictions for storage. String.
• The scope of state use. The context of the current request context can be accessed to Cookie,cookie is independent for each user.
• Storage size limit. Each cookie does not exceed 4K data. No more than 20 cookies per Web site. All Web sites have no more than 300 cookie totals.
• life cycle. Each cookie has its own expiration time, exceeding the expiration date.
• Safety and performance. Stored on the client, poor security. For sensitive data it is recommended that you store it after encryption.
• Advantages and disadvantages and precautions. It is easy to associate sites and users and save user settings for a long time.

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.