How to Use Asp.net cookies

Source: Internet
Author: User

1. What is Cookie?
Cookie is a short text message that is transmitted between the Web server and the browser along with user requests. Each time a user accesses a site,

Web ApplicationsProgramCan read the information contained in the cookie.
Assume that when a user requests a page of your website, your application not only returns the requested page. Returns a date that contains the specified date.

And time cookie. The user's browser also obtains the cookie while obtaining the page, and the cookie is saved on the client.

Folder.
2. Cookie restrictions
Most browsers support up to 4096 bytes (about 4 kb) of cookies. the browser also limits that a site can be saved on the client.

Number of cookies. Most browsers allow up to 20 cookies per site. If you try to save more cookies, the previous cookies

Will be deleted. Some browsers also limit the total number of cookies from all sites, which is usually 300.
3. How to Create a cookie
Specify the values when creating a cookie. Initially, you must specify the cookie name and the value to be saved. You can also create multiple

Cookie. However, the name of each Cookie must be unique for identification in future. (Cookies are stored by name, so you need to create

Two cookies with the same name will overwrite the previous one .)
You can also specify the expiration date and time for the cookie. The cookie is written to the user's hard disk and may remain on the disk all the time. Because

You can specify the cookie expiration date and time. When a user visits your site next time, the browser will first check the location of your site

If a cookie has expired, the browser will not send the cookie to the server along with the page request, but will delete it.

This expired cookie. (your site may already have multiple cookies written to your disk. However, the expiration date and

Time ). The browser is responsible for the cookies on the disk, which will affect the use of cookies by your applications.
If the cookie validity period is not set, you can still create a cookie (we call it a session cookie). The session cookie will not be saved to

Disk, but saved in memory. As part of user session information. If the user closes the browser or the session times out, the cookie will

Deleted. This non-permanent cookie.

4. How to Create a cookie
You can create a cookie in multiple ways and place the cookie object in the response. Cookies collection. Return

Browser.
First:
Response. Cookies ("cookiename"). value = "aaaa"; // create a cookie named cookiename.

The value stored in is AAAA.
Response. Cookies ("cookiename"). expires = datetime. Now. adddays (1); // specify the cookie expiration time as one day.
Second:
Httpcookie acookie = new httpcookie (cookiename); // create a cookie in the httpcookie class and specify

Cookie name
There is also an overloaded constructor.
Httpcookie acookie = new httpcookes (cookiename, cookievalue); // For detailed usage, refer to msdn.
// Same as the first method, you must specify the cookie expiration time.
Acookie. expires = datetime. Now. adddays (1); // The expiration time is 1 day.
// Acookie. value = "aaaa"; you can also assign a value to the cookie.
Response. Cookies. Add (acookie); then written to the browser
Note: The cookie validity period must be of the datetime type. The Value Attribute of Cookie must be of the string type (No

Is a string type and must be transformed) because any value in the cookie is ultimately saved as a string.
5. multi-value cookie (subkey)
You can also save multiple name/value pairs in a cookie. Name/value pairs are also called "keys" or "subkeys ". (If you are familiar with the URL, you will send

The subkeys and query strings are very similar ).
6 . How to Create a cookie with a bind key In fact, it is basically the same as the cookie creation statement. We can improve the above example.
See the following example.
First:
Response. Cookies ("cookiename") ("cookiechildname") = "cookievalue ";//
Create a cookie named cookiename, and then assign a value to the subkey.
Is it similar to creating a cookie together?
Response. Cookies ("cookiename"). expires = datetime. Now. adddays (1 );//
Specify the expiration date for the cookie. Like creating a cookie, you can specify the cookie name.
Second:
Httpcookie acookie = new httpcookie (cookiename); // create a cookie object
I will not write the reload.
Acookie. Values ["cookiename"] = "cookievalue"; // create a subkey under the cookie and assign the value
This is not a value but a values set attribute. We know that the collection set can be accessed through the index.
Acookie. expires = datetime. Now. adddays (1); // specify an expiration date for the cookie.
Response. Cookies. Add (acookie); // write the cookie to the browser.

Basically, it is the same as creating a cookie without a key. For more information, see msdn.

7. How to Control cookies
By default, all the cookies of a site are stored on the client, and these cookies are sent along with requests sent to the site.

To the server. That is to say, every page of the site can get all the cookies of the site.
To restrict a cookie to a folder on the server, set the path attribute of the cookie as follows:
Httpcookie acookie = new httpcookie (cookiename );
Acookie. value = "aaaa ";
Acookie. expires = datetime. Now. adddays (1 );
Acookie. Path =/application;
Response. Cookies. Add (acookie );
The path can be a physical path under the root directory of the site or a virtual root directory. In this way, Cookie can only be used as an application

Folder or a page in the virtual root directory. For example, if your website is www.gouku.com
In the preceding example, the cookie can be generated only at http://www.gouku.com/application/and under this folder.

And does not apply to pages of other applications, such as http://www.gouku.com/test/or

Http://www.gouku.com/next page.
Tip: test the internetexplorer and Mozilla browsers to find that the path used here is case sensitive. Average

The URLs on Windows servers are case-insensitive, except in this case. You cannot control how users enter URLs in browsers

However, if your application depends on cookies related to specific paths, make sure that the URLs in all the hyperlinks you create correspond

The path property value is case-insensitive.
Restrict the valid range of cookies to the domain
By default, cookies are associated with specific domains. For example, if your website is www.contoso.com

When you request a page, the cookie you wrote is sent to the server. (Except for cookies with specific path values, which I explained in the previous section

.) If your site has subdomains (such as contoso.com, sales.contoso.com, and support.contoso.com), you can

associate cookies with specific subdomains . Therefore, you need to set the domain attribute of the cookie as follows:
response. cookies ("cookiename "). value = datetime. now. tostring
response. cookies ("cookiename "). expires = datetime. now. adddays (1)
response. cookies ("cookiename "). domain = "support.contoso.com"
If the domain is set in this way, the cookie can only be used to specify the page in the subdomain.
You can also use the domain attribute to create cookies that can be shared in multiple subdomains. For example, set the domain as follows:
response. cookies ("cookiename "). value = datetime. now. tostring
response. cookies ("cookiename "). expires = datetime. now. adddays (1)
response. cookies ("cookiename "). domain = "contoso.com"
in this way, the cookie can be used in the primary domain, sales.contoso.com, and support.contoso.com
8. how to read a cookie
when a browser sends a request to the server, the cookie on the server is returned along with the request page. You can use the request object to read the cookie.

Cookie. The method for reading cookies is very similar to that for writing cookies to response objects.
See the following example:
Method 1:
String info = request. Cookies ["cookiename"]. value; // obtain the value through the index
Is it similar to response. Cookies ("cookiename"). value = info?
Method 2
Httpcookie acookie = request. Cookie ("cookiename"); // obtain the acookie object through the request
Acookie. value; // the value obtained through the value attribute is basically similar to the response usage.
// Make sure that the cookie exists before obtaining it. Otherwise, you will get a system. nullreferenceexception

Exception. It is best to display the cookie content on the page before. Use server. htmlencode () to encode the cookie content. To ensure the use

No cookie added to the user
The executable simplified version.
9. How to read the cookie of the BIND key
Similar to reading cookies
Method 1:
String info = request. Cookie ["cookiename"] ["cookiechildname"]; // corresponds
Response. Cookie ["cookiename"] ["cookiechildname"] = info
Method 2:
Httpcookie acookie = request. Cookie ["cookiname"] ["cookiechildname"]

========================================================== ======================================

I found some other materials.

// Remove existing conditional cookies
Private   Void Removewherecookie ( String   Where )
{
Httpcookie = Request. Cookies [ " Admin_harborspot_where " ];
Cookie. Value =   Where ;
Cookie. Expires = Datetime. Now. adddays ( - 3d );
Response. Cookies. Add (cookie );
}

========================================================== ==================================

Httpcookie cookie = new httpcookie ("aspcn ");

Cookie. Values. Add ("webmaster", "Flying knife ");

Cookie. Values. Add ("Writer", "beige ");

Cookie. Values. Add ("linkcolor", "blue ");

Response. appendcookie (cookie );

Retrieving information is as easy as possible

Httpcookie cookie = request. Cookies ["aspcn"];

Value1 = cookies. Values ["webmaster"];

Value2 = cookies. Values ["Writer"];

========================================================== ==================================

It is best to use this reading method: Server. htmlencode
If (request. Cookies ["username"]! = NULL)
{
Response. Write (Server. htmlencode(Request. Cookies ["username"]. Value ));
}

Read with subkeys:
If (request. Cookies ["user"]! = NULL)
{
Response. Write (Server. htmlencode(Request. Cookies ["user"] ["username"]. Value ));

}

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.