C # use cookie
A cookie is generated by the server and sent to the User-Agent (usually a browser). The browser saves the key/value of the cookie to a text file in a directory, the cookie is sent to the server when the same website is requested next time (provided that the browser is set to enable the cookie ). The cookie name and value can be defined by the server. for JSP, JSESSIONID can be directly written, so that the server can know whether the user is valid and whether to log on again, the server can set or read information contained in cookies to maintain the state of the user's session with the server.
The above is the theoretical knowledge of cookies. The following describes how to use cookies in C.
// Cookie writing case:
Protected void button#click (Object sender, eventargs E)
{
Httpcookie cookie = new httpcookie ("mycook"); // initialize and set the cookie name
Datetime dt = datetime. now;
Timespan Ts = new timespan (0, 0, 1, 0, 0); // The expiration time is 1 minute.
Cookie. expires = DT. Add (TS); // set the expiration time
Cookie. Values. Add ("userid", "userid_value ");
Cookie. Values. Add ("userid2", "userid2_value2 ");
Response. appendcookie (cookie );
// Output all content of the cookie
// Response. Write (cookie. Value); // The output is: userid = userid_value & userid2 = userid2_value2
}
// Cookie reading case:
Protected void button2_click (Object sender, eventargs E)
{
// Httpcookie Cokie = new httpcookie ("mycook"); // initialize
If (request. Cookies ["mycook"]! = NULL)
{
// Response. Write ("the key value in the cookie is userid:" + request. Cookies ["mycook"] ["userid"]); // The whole line
// Response. Write ("the key value in the cookie is userid2" + request. Cookies ["mycook"] ["userid2"]);
Response. Write (request. Cookies ["mycook"]. Value); // output all values
}
}
// Cookie modification case:
Protected void button3_click (Object sender, eventargs E)
{
// Obtain the cookie object of the Client
Httpcookie COK = request. Cookies ["mycook"];
If (COK! = NULL)
{
// Two methods for Cookie Modification
COK. Values ["userid"] = "alter-value ";
COK. Values. Set ("userid", "alter-value ");
// Add new content to the cookie
COK. Values. Set ("newid", "newvalue ");
Response. appendcookie (COK );
}
}
// Cookie deletion case:
Protected void button4_click (Object sender, eventargs E)
{
Httpcookie COK = request. Cookies ["mycook"];
If (COK! = NULL)
{
If (! Checkbox1.checked)
{
COK. Values. Remove ("userid"); // remove the value whose key value is userid
}
Else
{
Timespan Ts = new timespan (-1, 0, 0, 0 );
COK. expires = datetime. Now. Add (TS); // Delete the entire cookie, as long as the expiration time is set to the current
}
Response. appendcookie (COK );
}
}
C # use cookie