How to use asp.net cookies

Source: Internet
Author: User
Tags add time datetime html encode time and date subdomain

Asp tutorial. net cookie usage

Cookie provides a way to store user-specific information in web applications. For example, when a user accesses your site, you can use cookies to store user preferences or other information. When the user visits your website again, the application can retrieve the previously stored information.

 

If (page. request. cookies [domain] = null)
            {
Httpcookie cookies = new httpcookie (domain); // defines the cookie object
Cookies. values [keys] = values;
Datetime dts = datetime. now; // defines the time object
Timespan ts = new timespan (0, 0, 20, 0); // cookie effective time
Cookies. expires = dts. add (ts); // add time
// Cookies. domain = ".hnzbtb.com"; common subdomain names
Page. response. cookies. add (cookies );
            }
Else
            {
Httpcookie cookies = page. request. cookies [domain];
Cookies. values [keys] = values;
Datetime dts = datetime. now; // defines the time object
Timespan ts = new timespan (0, 0, 20, 0); // The time when the cookie is valid. For details, refer to the msdn
Cookies. expires = dts. add (ts); // add time
// Cookies. domain = ".hnzbtb.com ";
Page. response. cookies. add (cookies );
            }


 

Control the cookie range
By default, all cookies of a site are stored on the client together, and all cookies are sent to the server together with any requests sent to the site. That is to say, each page of a website can obtain all the cookies of the site. However, you can set the cookie range in two ways:

Restrict the cookie range to a folder on the server, which allows you to restrict the cookie to an application on the site.

Set the range to a domain, which allows you to specify which subdomains in the domain can access cookies.

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

Vbc # c ++ f # jscript
Copy dim appcookie as new httpcookie ("appcookie ")
Appcookie. value = "written" & datetime. now. tostring ()
Appcookie. expires = datetime. now. adddays (1)
Appcookie. path = "/application1"
Response. cookies. add (appcookie)
Note:


You can also write a cookie by adding the cookie directly to the cookie set, as shown in the previous example.
 

The path can be a physical path under the root directory of the site or a virtual root directory. The result is that the cookie can only be used for pages in the application1 folder or virtual root directory. For example, if your site name is www.contoso.com, the cookie created in the previous example will only be used for pages that path to the http://www.contoso.com/application1/ and all pages under the folder. However, cookies cannot be used for pages in other applications, such as pages in http://www.contoso.com/application2/ or http://www.contoso.com.

Note:
In some browsers, the path is case sensitive. You cannot control how users type URLs in their browsers, but if the application depends 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 cookie domain range
By default, cookies are associated with specific domains. For example, if your website is www.contoso.com, when a user requests any page from the site, the cookie you write will be sent to the server. (This may not include cookies with specific path values .) If a site has subdomains (for example, contoso.com, sales.contoso.com, and support.contoso.com), you can associate cookies with specific subdomains. To perform this operation, set the domain attribute of the cookie, as shown in the following example:

Vbc # c ++ f # jscript
Copy response. cookies ("domain"). value = datetime. now. tostring ()
Response. cookies ("domain"). expires = datetime. now. adddays (1)
Response. cookies ("domain"). domain = "support.contoso.com"


When the domain is set in this way, the cookie can only be used for pages in the specified subdomain. You can also use the domain attribute to create cookies that can be shared among multiple subdomains, as shown in the following example:

Vbc # c ++ f # jscript
Copy response. cookies ("domain"). value = datetime. now. tostring ()
Response. cookies ("domain"). expires = datetime. now. adddays (1)
Response. cookies ("domain"). domain = "contoso.com"
Then, the cookie can be used for the primary domain, or for the sales.contoso.com and support.contoso.com domains.

Read cookie
When a browser sends a request to the server, the cookie of the server is sent along with the request. In the asp.net tutorial application, you can use the httprequest object to read cookies. This object can be used as the request attribute of the page class. The structure of the httprequest object is basically the same as that of the httpresponse object. Therefore, you can read cookies from the httprequest object in the same way as writing cookies to the httpresponse object. The following code example demonstrates two methods. You can obtain the cookie value named username through these two methods and display the value in the label control:

Vbc # c ++ f # jscript
Copy if not request. cookies ("username") is nothing then
Label1.text = server.html encode (request. cookies ("username"). value)
End if

If not request. cookies ("username") is nothing then
Dim acookie as httpcookie = request. cookies ("username ")
Label1.text = server.html encode (acookie. value)
End if

Before trying to obtain the cookie value, make sure that the cookie exists. If the cookie does not exist, an nullreferenceexception will be returned. Note that you must call the htmlencode method to encode the cookie content before displaying the cookie content on the page. This prevents malicious users from adding executable scripts to cookies. For more information about cookie security, see "cookie and security.

Note:
Because different browsers store cookies in different ways, different browsers on the same computer do not need to be able to read each other's cookies. For example, if you use internet explorer to test a page and then use another browser for testing, the latter will not find the cookie saved by internet explorer.
 

The method for reading the cookie neutron key value is similar to that for setting this value. The following code example shows how to obtain the subkey value:

Vbc # c ++ f # jscript

Copy if not request. cookies ("userinfo") is nothing then
Label1.text = _
Server.html encode (request. cookies ("userinfo") ("username "))
Label2.text = _
Server.html encode (request. cookies ("userinfo") ("lastvisit "))
End if


In the preceding example, the code reads the value of the sub-key lastvisit, which is previously set as a string representation of the datetime Value. Cookie stores the value as a string. Therefore, to use the lastvisit value as a date, you must convert it to an appropriate type, as shown in the following example:

Vbc # c ++ f # jscript
Copy dim dt as datetime
Dt = datetime. parse (request. cookies ("userinfo") ("lastvisit "))
The subkeys in cookies are converted into namevaluecollection collections. Therefore, another way to obtain a single sub-key is to obtain the sub-key set and then extract the sub-key value by name, as shown in the following example:

Vbc # c ++ f # jscript

Copy if not request. cookies ("userinfo") is nothing then
Dim userinfocookiecollection _
System. collections. specialized. namevaluecollection
Userinfocookiecollection = request. cookies ("userinfo"). values
Label1.text = _
Server.html encode (userinfocookiecollection ("username "))
Label2.text = _
Server.html encode (userinfocookiecollection ("lastvisit "))
End if


Change cookie expiration date
The browser is responsible for cookie management, and the cookie expiration time and date can help the browser manage cookie storage. Therefore, although the cookie name and value can be read, the cookie expiration date and time cannot be read. When the browser sends cookie information to the server, the validity period is not included. (The cookie's expires attribute always returns a datetime value of 0 .) If you are worried about the cookie expiration date, you must reset the cookie. This process is described in the "modify and delete cookie" section.

Note:
You can read the expires attribute of the cookie set in the httpresponse object before sending the cookie to the browser. However, you cannot obtain the validity period from the returned httprequest object.
 

Read cookie set
Sometimes, you may need to read all the cookies available for the page. To read the names and values of all cookies available for the page, you can use the following code to use cookies in sequence.

Vbc # c ++ f # jscript

Copy dim I as integer
Dim output as system. text. stringbuilder = new system. text. stringbuilder
Dim acookie as httpcookie
For I = 0 to request. cookies. count-1
Acookie = request. cookies (I)
Output. append ("cookie name =" & server.html encode (acookie. name )_
& "<Br/> ")
Output. append ("cookie value = "&_
Server.html encode (acookie. value) & "<br/> ")
Next
Label1.text = output. tostring ()


Note:
When running this code, you may see a cookie named asp.net _ sessionid. Asp.net uses this cookie to store the unique identifier of your session. Session cookies are not stored on your hard disk. For more information about session cookies, see the "cookie and session status" section after this topic.
 

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.