Asp tutorial. net cookie operations
Cookie limit to a folder or application
Httpcookie appcookie = new httpcookie ("appcookie ");
Appcookie. value = "written" + datetime. now. tostring ();
Appcookie. expires = datetime. now. adddays (1 );
Appcookie. path = "/application1 ";
Response. cookies. add (appcookie );
Clear cookie
Httpcookie cookie = request. cookies ["username"];
Cookie. expires = datetime. now. adddays (-30 );
Response. cookies. add (cookie );
Cookie operation
Response. cookies ["userinfo"] ["username"] = "patrick ";
Response. cookies ["userinfo"] ["lastvisit"] = datetime. now. tostring ();
Response. cookies ["userinfo"]. expires = datetime. now. adddays (1 );
Httpcookie acookie = new httpcookie ("userinfo ");
Acookie. values ["username"] = "patrick ";
Acookie. values ["lastvisit"] = datetime. now. tostring ();
Acookie. expires = datetime. now. adddays (1 );
Response. cookies. add (acookie );
Under normal conditions, 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 cookie parameters in two ways.
Restrict the cookie domain range
Response. cookies ["domain"]. value = datetime. now. tostring ();
Response. cookies ["domain"]. expires = datetime. now. adddays (1 );
Response. cookies ["domain"]. domain = "support.contoso.com ";
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:
If (request. cookies ["username"]! = Null)
Label1.text = server.html encode (request. cookies ["username"]. value );
If (request. cookies ["username"]! = Null)
{
Httpcookie acookie = request. cookies ["username"];
Label1.text = server.html encode (acookie. value );
}