Learn how to use cookie Programming

Source: Internet
Author: User
Tags allkeys subdomain

What is Cookie?
Cookie is a short text message that is transmitted between the Web server and the browser as user requests and pages. Each time a user accesses a site, the Web ApplicationProgramCan read the information contained in the cookie. The most fundamental purpose of cookies is that they can help websites save information about visitors. To put it more simply, cookie is a way to maintain the continuity of Web applications (that is, to execute "state management.

I have referred to the last article on cookies in xxol.net. It took nearly a week to release this article and provided the C # source code. The original Article was developed with VB.net. Although I heard it was a Microsoft tutorial, there are still some programs that cannot be transplanted directly (it may be that the. NET Framework version is earlier when the tutorial is written ). However, I promise that the C # program I provide can be fully debugged in. NET Framework 1.1.

If you are interested in this text, I am willing to provide text reprint authorization under the premise of Creative Commons license. Of course, if you have any questions about this article, please send me a message (mailto: Ryun dot CN (a) gmail dot com) or leave a message in the comment below the body.

Article Summary (Created by Macromedia flashpager 2 ):
Open Link Source Codes (Created by Visual Studio. NET 2003 ):
Download codes password: Ryun.cn

Cookie restrictions
Most browsers support 20 up to 4096-byte cookies for each site. If you try to save more cookies, the first cookie will be deleted. The most likely cookie restriction is that users can set their own browsers to reject cookies. Although cookies are very useful in applications, applications should not rely on the ability to save cookies. Cookies can be icing on the cake, but do not use them to support key functions.

Compile cookie
You can useResponseAttribute to compile the cookie. The object provided by this attribute allows you to add information to the information displayed by the page to the browser. The response object supportsCookiesYou can add the cookie to which the browser is to be written. You can add cookies to the response. Cookies set in multiple ways:

Response. Cookies ["username"]. value = "Ryun ";
Response. Cookies ["username"]. expires = datetime. Now. adddays (1 );

Httpcookie acookie = new httpcookie ("lastvisit ");
Acookie. value = datetime. Now. tostring ();
Acookie. expires = datetime. Now. adddays (1 );
Response. Cookies. Add (acookie );

The first cookie is directly setResponse. CookiesSet value. You can use this method to add values to the set, becauseResponse. CookiesYesfromNameobjectcollectionbaseDerived from a special set of types. The second is to create an instance of the cookie object (HttpcookieType), and set its properties, and thenAddMethod to add itResponse. CookiesSet. InstantiationHttpcookieYou must pass the cookie name as part of the constructor.

View cookie
It is easy to view cookies. Internet Explorer is used as an example: "Tools"> "Internet Options"> "general"> "Settings"> "view files"> "Cookie: "starts with the cookie file.

Multi-value cookie (subkey)
You can also save multiple name/value pairs in a cookie. Name/value pairs are also called "keys" or "subkeys". For example, if you do not want to create two separate cookies named "username" and "lastvisit, you can create a cookie named "userinfo" and make it contain two subkeys: "username" and "lastvisit ".

The following example shows two different methods for compiling the same cookie. Each Cookie has two subkeys:

Response. Cookies ["userinfo"] ["username"] = "Ryun ";
Response. Cookies ["userinfo"] ["lastvisit"] = datetime. Now. tostring ();
Response. Cookies ["userinfo"]. expires = datetime. Now. adddays (1 );

Httpcookie acookie = new httpcookie ("userinfo ");
Acookie. Values ["username"] = "Ryun ";
Acookie. Values ["lastvisit"] = datetime. Now. tostring ();
Acookie. expires = datetime. Now. adddays (1 );
Response. Cookies. Add (acookie );

Control the valid cookie range
You can set the valid range of a cookie in two ways. One is to restrict the valid range of a cookie to a folder on the server, in fact, the cookie is restricted to an application on the site. The other is to set the valid range to a domain, allowing you to specify which subdomains in the domain can be accessed.

Httpcookie appcookie = new httpcookie ("appcookie ");
Appcookie. value = "written" + datetime. Now. tostring ();
Appcookie. expires = datetime. Now. adddays (1); appcookie. Path = "/ruly ";
Response. Cookies. Add (appcookie );

To restrict a cookie to a folder on the server, use the preceding method to restrict the path attribute of the cookie to the "/ruly" folder ).Tip:By testing Internet Explorer and Mozilla browsers, we found that the paths used here are case sensitive.

If the domain is set as follows, the cookie can be used to specify the page in the subdomain. (Valid only at "http://ruly.ryun.cn)

Response. Cookies ["subcookie"]. value = datetime. Now. tostring ();
Response. Cookies ["subcookie"]. expires = datetime. Now. adddays (1 );
Response. Cookies ["subcookie"]. Domain = "ruly.ryun.cn ";

You can use the following method to apply the cookie to the primary domain (ryun.cn) and subdomain (ruly.ryun.cn:

Response. Cookies ["subcookie"]. value = datetime. Now. tostring ();
Response. Cookies ["subcookie"]. expires = datetime. Now. adddays (1 );
Response. Cookies ["subcookie"]. Domain = "ryun.cn ";

Read cookie
When a browser sends a request to the server, the cookie of the server is sent together with the request. In Asp.net, you can use the request object to read cookies. The following example shows two methods to obtain the cookie value named "username" and display the value in the label control:

String stroutput = "";
If (request. Cookies ["username"]! = NULL)
{
Stroutput = server. htmlencode (request. Cookies ["username"]. value );
}
If (request. Cookies ["lastvisit"]! = NULL)
{
Httpcookie acookie = request. Cookies ["lastvisit"];
Labinfo. Text = stroutput + "" + server. htmlencode (acookie. value );
}

Before obtaining the cookie value, make sure that the cookie exists. Otherwise, you will getSystem. nullreferenceexceptionException.Note:: It is recommended to callHttpserverutility. htmlencodeMethod to encode the cookie content. This is because I want to display the cookie content andMake sure there are no malicious executable scripts in the cookie. In addition, different browsers on the same computer may not be able to read their cookies from each other.

The following is a method to obtain the subkey value:

String stroutput = "";
If (request. Cookies ["userinfo"]! = NULL)
{
Stroutput = server. htmlencode (request. Cookies ["userinfo"] ["username"]);
Labinfo. Text = stroutput + "" + server. htmlencode (request. Cookies ["userinfo"] ["lastvisit"]);
}

Cookie stores the value in the form of a string. To use the lastvisit value as a date, you must convert it:

Datetime DT;
Dt = convert. todatetime (request. Cookies ["userinfo"] ["lastvisit"]);

The cookie subkey type isNamevaluecollectionType. Therefore, another way to obtain a single sub-key is to first obtain the sub-key set and then extract the sub-key value by name, as shown below:

If (request. Cookies ["userinfo"]! = NULL)
{
System. Collections. Specialized. namevaluecollection userinfocookiecollection;
Userinfocookiecollection = request. Cookies ["userinfo"]. values;
Stroutput = server. htmlencode (userinfocookiecollection ["username"]);
Labinfo. Text = stroutput + "" + server. htmlencode (userinfocookiecollection ["lastvisit"]);
}

Read Cookie set
To read the names and values of all cookies available for the page, you can use the followingCodeTraverse the request. Cookies set:

String stroutput = "";
Httpcookie acookie;
For (INT I = 0; I <= request. Cookies. Count-1; I ++)
{
Acookie = request. Cookies [I];
Stroutput + = "<p> cookie name =" + server. htmlencode (acookie. Name) + "<br/> ";
Stroutput + = "cookie value =" + server. htmlencode (acookie. Value) + "</P> ";
}
Labinfo. Text = stroutput;

Note:You may see a cookie named "ASP. net_sessionid", which stores the unique identifier of your session. It will not be permanently stored on the hard disk.

If a cookie has a subkey, it is displayed as a separate name/value string. CookieHaskeysThis attribute tells you whether the cookie has a subkey. If you have a sub-key, you can drill down in the sub-key set to obtain the names and values of each sub-key. You can alsoValuesTo obtain information about the sub-key. This attribute is of the type.Namevaluecollection. You can directly read the sub-key value from the values set based on the index value. The corresponding sub-key value can be a member of the values set.AllkeysThe member returns a string set.

In the following example, the haskeys attribute is used to test the child key. If the child key is detected, the Child key is obtained from the values set:

String stroutput = "", subkeyname = "", subkeyvalue = "";
Httpcookie acookie;

For (INT I = 0; I <= request. Cookies. Count-1; I ++)
{
Acookie = request. Cookies [I];
Stroutput + = "Cookie name =" + acookie. Name + "<br/> ";
If (acookie. haskeys)
{
For (Int J = 0; j <= acookie. Values. Count-1; j ++)
{
Subkeyname = server. htmlencode (acookie. Values. allkeys [J]);
Subkeyvalue = server. htmlencode (acookie. Values [J]);
Stroutput + = "<p> sub cookie name =" + subkeyname + "<br/> ";
Stroutput + = "sub cookie value =" + subkeyvalue + "</P> ";
}
}
Else
Stroutput + = "cookie value =" + server. htmlencode (acookie. Value) + "<br/> ";
Labinfo. Text = stroutput;
}

You can also use the subkeyNamevaluecollectionObject extraction:

String stroutput = "", subkeyname = "", subkeyvalue = "";
Httpcookie acookie;

For (INT I = 0; I <= request. Cookies. Count-1; I ++)
{
Acookie = request. Cookies [I];
Stroutput + = "Cookie name =" + acookie. Name + "<br/> ";
If (acookie. haskeys)
{
System. Collections. Specialized. namevaluecollection cookievalues = acookie. values;
String [] cookievaluenames = cookievalues. allkeys;
For (Int J = 0; j <= cookievalues. Count-1; j ++)
{
Subkeyname = server. htmlencode (cookievaluenames [J]);
Subkeyvalue = server. htmlencode (cookievalues [J]);
Stroutput + = "<p> sub cookie name =" + subkeyname + "<br/> ";
Stroutput + = "sub cookie value =" + subkeyvalue + "</P> ";
}
}
Else
Stroutput + = "cookie value =" + server. htmlencode (acookie. Value) + "<br/> ";
Labinfo. Text = stroutput;
}

Note:Remember, the reason why I call the server. htmlencode method is that I want to display the cookie value on the page. If you only test the cookie value, you do not need to encode it before use.

Modify and delete cookies
Modifying a cookie actually means creating a new cookie with a new value and sending the cookie to the browser to overwrite the old cookie on the client.

The following example shows how to change the cookie value used to store the number of site visits:

Int intcounter = 0;
If (request. Cookies ["counter"]! = NULL)
Intcounter = convert. toint16 (request. Cookies ["counter"]. value );
Intcounter ++;
Response. Cookies ["counter"]. value = intcounter. tostring ();
Response. Cookies ["counter"]. expires = datetime. Now. adddays (1 );
Labinfo. Text = server. htmlencode (request. Cookies ["counter"]. value );

Another method:

Httpcookie ctrcookie;
Int intcounter = 0;
If (request. Cookies ["counter"]! = NULL)
Ctrcookie = request. Cookies ["counter"];
Else
Ctrcookie = new httpcookie ("counter ");
Intcounter = convert. toint16 (ctrcookie. value );
Intcounter ++;
Ctrcookie. value = intcounter. tostring ();
Ctrcookie. expires = datetime. Now. adddays (1 );
Response. Cookies. Add (ctrcookie );
Labinfo. Text = server. htmlencode (request. Cookies ["counter"]. value );

Delete cookie
Deleting a cookie is only a form of modifying a cookie through a browser. The method for modifying a cookie has been described above (that is, to create a new cookie with the same name). The difference is to set its validity period to a previous date. When the browser checks the cookie validity period, the expired cookie is deleted.

The following example is a little more interesting than deleting a single cookie. You can use this method to delete all cookies in the current domain:

Httpcookie acookie;
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 );
Labinfo. Text + = "<br/> Delete" + acookie. Name + "done ...";
}

Modify or delete a subkey
The method for modifying a single subkey is the same as that for creating it at first:

Response. cookies ["userinfo"] ["lastvisit"] = datetime. now. tostring (); response. cookies ["userinfo"]. expires = datetime. now. adddays (1 );

However, you cannot simply reset the cookie expiration date, because you can only delete the entire cookie and cannot delete a single subkey. The actual solution is to operate on the values set of cookies containing sub-Keys. First, obtain the cookie from the request. Cookie object to recreate the cookie. Then, you can call the Remove Method of the values set and pass the sub-key name to be deleted to the Remove Method. Next, you can add the modified cookie to the response. Cookies set to send the modified cookie back to the browser.

String subkeyname = "username"; // define will be deleted sub-key name.
Httpcookie acookie = request. Cookies ["userinfo"];
Acookie. Values. Remove (subkeyname );
Acookie. expires = datetime. Now. adddays (1 );
Response. Cookies. Add (acookie );
Labinfo. Text + = "<br/> Delete" + acookie. Name + "." + subkeyname + "done ...";

Cookie and security
For applications, cookies are another form of user input, so they are easily obtained and used by others illegally. Because the cookie is stored on your computer, you can at least see the information you saved in the cookie. If you want to, you can modify the cookie before the browser sends it to you.Note:Do not store confidential information such as the user name, password, and credit card number in cookies. Do not save content that should not be controlled by users in cookies, or that may be controlled by others who steal cookies. Similarly, you should be skeptical about any information obtained from cookies. Do not think that the data you get is the information you originally imagined. The security measures used to process cookie values should be the same as those used to process data typed by users on the web page. Cookies are transmitted between browsers and servers in plain text. Anyone who can intercept web communication can read cookies. You can set the cookie attributes so that they can only be transmitted over connections that use Secure Sockets Layer (SSL, also known as https.

How can we safely use cookies in the face of these security issues? You can save unimportant data in cookies, such as user preferences or other information that has no significant impact on applications. If you do need to save some sensitive information (such as the user ID) in the cookie, encrypt the information. One feasible method is to use the ASP. Net Forms authentication utility to create an authentication ticket and save it as a cookie.

Check whether the browser accepts cookies
The following is a simple example to illustrate how to test whether a cookie is accepted. This example contains two pages: Create a cookie in the first page (create. aspx), and redirect the browser to the second page. The second page (read. aspx) tries to read this cookie, instead redirects the browser to the first page, and adds a query string variable with the test result to the URL. The following is the first page (create. aspx ):

Private void page_load (Object sender, system. eventargs E)
{
If (! Page. ispostback)
{
If (request. querystring ["acceptscookies"] = NULL)
{
Response. Cookies ["testcookie"]. value = "OK! ";
Response. Cookies ["testcookie"]. expires = datetime. Now. addminutes (1 );
Response. Redirect ("read. aspx? Redirect = "+ server. urlencode (request. url. tostring ()));
}
Else
Labinfo. Text = "accept cookie =" + request. querystring ["acceptscookies"];
}
}

The second receiving page (read. aspx) is shown below ):

Private void page_load (Object sender, system. eventargs E)
{
String redirect = request. querystring ["Redirect"];
String acceptscookies;
If (request. Cookies ["testcookie"] = NULL)
Acceptscookies = "0 ";
Else
{
Acceptscookies = "1 ";
Response. Cookies ["testcookie"]. expires = datetime. Now. adddays (-1 );
}
Response. Redirect (redirect + "? Acceptscookies = "+ acceptscookies, true );
}

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.