Use of cookies in ASP. NET Programming

Source: Internet
Author: User
Tags set cookie
Cookie used for ASP. NET Programming cookie is a Web application Program It provides a useful method to save user information. For example, when a user accesses your site, you can use cookies to save user preferences or other information, so that when the user visits your site next time, the application can retrieve previously saved information.

This article describes the application of cookies in ASP. NET applications. It shows you the technical details of cookie application in ASP. NET, such as compiling cookies and then reading them. In addition, we will introduce you to various features and special circumstances of cookies, as well as ASP. NET's support for cookies.

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 application can read the information contained in the cookie.

Assume that when a user requests to access a page on your website, your application sends more than a page to the user, but also a cookie containing the date and time. The user's browser obtains the cookie while obtaining the page, and saves it in a folder on the user's hard disk.

Later, if the user visits the page on your site again, when the user enters the URL, the browser will find the cookie associated with the URL on the local hard disk. If the cookie exists, the browser sends it along with the page request to your site, and your application can determine the date and time of the user's last visit to the site. You can send a message to the user based on this information, or check the expiration time or perform other useful functions.

Cookie is associated with a web site rather than a specific page. Therefore, no matter which page the user requests to visit the site, the browser and server will exchange cookie information of When a user accesses other sites, each site may send a cookie to the user's browser, and the browser will save all these cookies separately.

These are the basic operating principles of cookies. So what are the functions of cookies? The most fundamental purpose is that cookies 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. The browser and the Web server are always disconnected except for a short period of actual information exchange, and each request sent by the user to the Web server is processed independently, regardless of all other requests. However, in most cases, it is necessary for the Web server to identify you when you request a page. For example, a Web server on a shopping site tracks each shopper so that the site can manage shopping cart and other user-related information. Therefore, the cookie function is similar to a business card. It provides the relevant identification information to help the application determine how to proceed.

Cookie can be used for multiple purposes, all of which are to make the web site remember you. For example, a site that implements a public opinion test can simply use cookies as a Boolean value to indicate whether your browser has participated in the vote, thus avoiding repeated voting; websites that require user login can use cookies to determine whether you have logged on, so that you do not have to enter creden。 every time.

For more background information about cookies, we recommend that you read the article "How Internet cookies work" on the Verizon web site at,4065,1022z1,00.html ). The author explained in detail what cookies are and how they exchange information between browsers and servers. He also summarized the privacy issues related to cookies.

By the way, do you want to know why they are called "cookies "? Jargon file (also known as the new hacker's dictionary) version 4.3.3 provides an accurate definition and reasonable explanation of the term. You can go to /~ ESR/jargon/jargon.html # cookie (English) to find related entries.

In the subsequent content, this article assumes that you already know what a cookie is and that you know why to use a cookie in an ASP. NET application.


Cookie restrictions

Before discussing the technical details of cookies, I would like to introduce several restrictions on cookie applications. Most browsers support up to 4096 bytes of cookies. If you want to save a few values to your computer, this space is large enough, however, you cannot use a cookie to save a dataset or a large amount of other data. In practice, you may not want to save a large amount of user information in cookies, but only want to save user numbers or other identifiers. Then, when the user visits your site again, you can use this user ID to search for the user's details in the database. (For information on saving user information, see cookies and security .)

The browser also limits the number of cookies that your site can save on your computer. Most browsers only allow 20 cookies to be saved on each site. If you try to save more cookies, the first cookie will be deleted. Some browsers also limit the total number of cookies from all sites, which is usually 300.

The most likely cookie restriction is that users can set their own browsers to reject cookies. It is difficult for you to solve this problem unless you do not use cookies at all but use other mechanisms to save user-related information. A common method for saving user information is session status, which depends on cookies. This is described in the cookie and session status.

Note: For more information about status management and options used to save information in Web applications, see Introduction to web forms state (English) and State management recommendations (English ).
Even though cookies are 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. If your application must use cookies, you can test to determine whether the browser accepts cookies. I briefly introduced a test method in the section "check whether the browser accepts cookies" after this article.

Compile cookie

You can use the response attribute of the page to write cookies. The objects provided by this attribute allow you to add information to the information displayed by the page to the browser. The response object supports a set named cookies. You can add cookies to the set to be written into the browser.

Note: The response object and request object to be discussed below are the page attributes of the httpresponse (English) and httprequest (English) class instances respectively. For more information about response and request, see httpresponse and httprequest.

When creating a cookie, you must specify several values. Initially, you must specify the cookie name and the saved value. You can create multiple cookies. Each Cookie must have a unique name for future reading. (Cookies are saved by name. Therefore, if you create two cookies with the same name, the saved one overwrites the previous one .)

You may also want to specify the cookie expiration date and time. Cookies are generally written to your disk and may remain on the disk all the time. Therefore, you can specify the cookie expiration date and time. When a user visits your site again, the browser will first check the cookie set of your site. If a cookie has expired, the browser will not send the cookie to the server along with the page request, instead, delete the expired cookie. (Your Website may already have multiple cookies written on your computer. Each Cookie has its own expiration date and time .) Please note that the browser is responsible for managing cookies on the hard disk, which will affect your use of cookies in applications. I will introduce this soon.

How long should a cookie be valid? This depends on the purpose of the cookie. In other words, it depends on how long the cookie value is valid for your application. If you use cookies to count website visitors, you can set the validity period to one year. If a user has not accessed your site for one year, the user can be treated as a new visitor; if you use cookies to save your preferences, you can set them to always valid (for example, if they expire after 50 years), because it is troublesome for users to reset preferences on a regular basis. Sometimes, you may need to write a cookie that expires in seconds or minutes. In the section "check whether the browser accepts cookies" after this article, I will list an example in which the actual validity period of the cookie created in this example is only a few seconds.

Note: Do not forget that users can delete cookies on their computers at any time. Therefore, even if you have saved valid cookies for a long time, you can delete them all at your discretion, clear all settings saved in the cookie.

If you do not set the cookie validity period, you can still create a cookie, but it will not be saved to the user's hard disk, but will become part of the user's session information. If the user closes the browser or the session times out, the cookie will be deleted. This non-permanent cookie is suitable for storing information that only needs to be saved for a short period of time, or for storing information that should not be written to the customer's computer disk for security reasons. For example, if you are using a public computer and you do not want to write cookies to the disk of the computer, you can use non-permanent cookies.

You can add cookies to the response. Cookies set in multiple ways. The following example describes two methods to complete this task:

Response. Cookies ( " Username " ). Value =   " Mike "  
Response. Cookies ( " Username " ). Expires = Datetime. Now. adddays ( 1 )

Dim Acookie As   New Httpcookie ( " Lastvisit " )
Acookie. Value = Datetime. Now. tostring
Acookie. Expires = Datetime. Now. adddays ( 1 )
Response. Cookies. Add (acookie)

In this example, two cookies are added to the cookies set, one being "username" and the other being "lastvisit ". For the first cookie, I directly set the value of the response. Cookies set. You can use this method to add values to the set, because response. Cookies are derived from a special set of the nameobjectcollectionbase (English) type.

For the second cookie, I created an instance of the cookie object (httpcookie [English] type), set its attributes, and add it to the response. Cookies set through the add method. When instantiating an httpcookie object, you must pass the cookie name as part of the constructor.

The two examples have completed the same task, that is, writing a cookie to the browser. The method you want to use depends on your personal preferences. You may find that the second method is easier to set cookie attributes, but you will also notice that the difference between the two is not great.

In the two methods, the validity period value must be of the datetime type. The "lastvisited" value is also the date/time value. However, in this case, I must convert the date/time value to a string because any value in the cookie is saved as a string.

View your cookies

You may find it helpful to understand the effect of creating a cookie. It is easier to view cookies because they are all text files. The key is that you can find them. Different browsers store cookies in different ways. I will introduce how Internet Explorer saves cookies. If you are using another browser, please view the help of this browser to learn about Cookie processing.

An easy way to view cookies is to allow Internet Explorer to search for them. In Internet Explorer, select "Internet Options" from the "Tools" menu, click "Settings" on the "General" tab, and then click "view files ". Internet Explorer opens a window to display all temporary files, including cookies. Search for files starting with "Cookie:" or text files in the window. Double-click a cookie to open it in the default text file.

You can also find the text file of the cookie on the hard disk to open the cookie. Internet Explorer saves site cookies in the file named @ .txt, which is your account name. For example, if your name is mikepope and the site you visit is, the site's cookie is saved in a file named mikepope@www.contoso.txt. (The file name may contain an sequential number, for example, mikepope@www.contosow.1}.txt .)

This cookie text file is related to the user, so it will be saved separately according to the account. For example, in Windows XP, you can find the cookie file in the following directory:

C: \ Documents ents and Settings \ cookies

To find the latest cookie, you can sort the directory content by the modification date and find the most recently modified files.

You can use a text editor to open cookies. If the file contains multiple cookies, these cookies are separated by asterisks. The first line of each cookie is the name of the cookie, the second line is the value, and the other lines contain the daily processing information of the cookie, such as the expiration date and time. There is also a simple checksum in the cookie. If you change the length of the cookie name or value, the browser will detect the modification and delete the cookie.

Multi-value cookie (subkey)

In the preceding example, a cookie is used for each value (user name and last access time) to be saved. You can also save multiple name/value pairs in a cookie. Name/value pairs are also called "keys" or "subkeys", depending on what you read. (If you are familiar with the URL structure, you will find that the subkey is very similar to the query string in it .) 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 ".

There are many reasons for us to replace individual cookies with subkeys. Most obviously, it is more organized to put related or similar information in a cookie. In addition, because all information is in one cookie, Cookie attributes such as validity period apply to all information. (Of course, if you want to specify different expiration dates for different types of information, you should save the information in a separate cookie .)

Cookies With subkeys can also help you reduce the cookie size. As described in the previous section on cookie restrictions, the total size of a cookie is limited to 4096 bytes, and more than 20 Cookies cannot be saved for a website. Using a single cookie with the BIND key, the number of cookies on the site will not exceed 20. In addition, a cookie occupies a basic space overhead of about 50 characters (used to save the validity period information, etc.), plus the length of the saved value, the total number is close to 4 K. If you use five sub-keys instead of five individual cookies, you can save the basic space overhead of four cookies, saving about 200 bytes in total.

To create a cookie with the BIND key, you can use various syntaxes used to compile a single cookie. The following example shows two different methods for compiling the same cookie. Each Cookie has two subkeys:

Response. Cookies ( " Userinfo " )( " Username " ) =   " Mike "  
Response. Cookies ( " Userinfo " )( " Lastvisit " ) = Datetime. Now. tostring
Response. Cookies ( " Userinfo " ). Expires = Datetime. Now. adddays ( 1 )

Dim Acookie As   New Httpcookie ( " Userinfo " )
Acookie. Values ( " Username " ) =   " Mike "  
Acookie. Values ( " Lastvisit " ) = Datetime. Now. tostring
Acookie. Expires = Datetime. Now. adddays ( 1 )
Response. Cookies. Add (acookie)

Control the valid cookie range

By default, all the cookies of a site are stored on the client, and all these cookies are sent to the server together with the requests sent to the site. That is to say, each page of the site can obtain all the cookies of the site. However, you may want cookies to be more targeted. In this case, you can set the valid range of cookies in two ways:

Restrict the valid range of cookies to a folder on the server. In this way, the cookie is actually restricted to an application on the site.

Set the valid range to a domain to allow you to specify which subdomains in the domain can access cookies.

Restrict cookies to a folder or application

To restrict a cookie to a folder on the server, set the path attribute of the cookie as follows:

Dim Appcookie As   New Httpcookie ( " Appcookie " )
Appcookie. Value =   " Written "   & Now. tostring
Appcookie. Expires = Now. adddays ( 1 )
Appcookie. Path =   " /Application1 "  
Response. Cookies. Add (appcookie)

Of course, you can also directly set response. cookies to write cookies, as described above.

The path can be a physical path under the root directory of the site or a virtual root directory. In this way, the cookie can only be used for pages in the application1 folder or virtual root directory. For example, if your site is named, the cookie generated in the previous example can only be used for pages with paths of and all pages under the folder, rather than pages in other applications, such as pages under a or

Tip: We can test Internet Explorer and Mozilla browsers to find that the paths used here are case sensitive. Generally, URLs on Windows servers are case-insensitive, except in this case. You cannot control how users enter URLs in browsers. However, if your applications depend on cookies related to specific paths, make sure that the URL in all the hyperlinks you create matches the case of the path property value.

Restrict the valid range of cookies to the domain

By default, cookies are associated with specific domains. For example, if your website is, when a user requests a page from the site, the cookie you wrote will be sent to the server. (Except for cookies with specific path values, which I have explained in the previous section .) If your site has subdomains (such as,, and, you can associate cookies with specific subdomains. Therefore, you need to set the domain attribute of the cookie as follows:

Response. Cookies ( " Domain " ). Value = Datetime. Now. tostring
Response. Cookies ( " Domain " ). Expires = Datetime. Now. adddays ( 1 )
Response. Cookies ( " Domain " ). Domain =   " "  

If you set the domain 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 sub-domains. For example, set the domain as follows:

Response. Cookies ( " Domain " ). Value = Datetime. Now. tostring
Response. Cookies ( " Domain " ). Expires = Datetime. Now. adddays ( 1 )
Response. Cookies ( " Domain " ). Domain =   " "  

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: 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.