The basic learning of Cookie programming in ASP. NET is as follows:
Cookie-related restrictions in ASP. NET:
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 details about status Management and options used to save information in Web applications, see Introduction to Web Forms State in English) and State Management Recommendations in 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.
Cookie programming basics in ASP. NET
You can use the Response (English) attribute of the page to compile 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 in English. 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 class instance, including HttpResponse (English) and HttpRequest (English. 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. The Cookie is 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 of which 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, expiration 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 Based on Cookie programming in ASP. NET
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 www.contoso.com, the site's Cookie is saved in a file named mikepope@www.contoso.txt. The file name may contain an sequential number, such as 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 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 user name and last access time of the value 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 consumes about 50 characters of basic space for saving validity period information, and so on), 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 www.contoso.com, the Cookie generated in the previous example can only be used for pages with paths of http://www.contoso.com/Application1/ and all pages under the folder, rather than pages in other applications, such as pages under a http://www.contoso.com/Application2/ or http://www.contoso.com.
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 www.contoso.com, 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, I have explained them 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("domain").Value = DateTime.Now.ToString
- Response.Cookies("domain").Expires = DateTime.Now.AddDays(1)
- Response.Cookies("domain").Domain = "support.contoso.com"
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 = "contoso.com"
In this way, the Cookie can be used for the primary domain, sales.contoso.com, and support.contoso.com.
The Cookie programming basics in ASP. NET are introduced here. I hope you have some knowledge about the Cookie programming basics in ASP. NET.
- Examples of ASP. NET File Upload controls
- Nine steps for learning ASP. NET
- Advantages of ASP. NET compared with ASP
- Analysis of ASP. NET MD5 and SHA1 encryption methods
- ASP. NET learning-CSS implementation multi-interface two methods