.. NET provides multiple methods for reading and writing cookies. cookies are Cookies transmitted from the client to the server in the form of Cookie headers; Response. cookies are created on the server and transmitted to the client in the form of Set-Cookie header. That is to say, one is sent from the client to the server, and the other is sent from the server to the client.
When you create Cookies for the first time, the following two reading methods read the same content:
C # code
HttpCookie hc = new HttpCookie ("User2 ");
Hc ["UserName"] = "mengxianhui ";
Response. Cookies. Add (hc );
Response. Cookies ["User1"] ["UserId"] = "net_lover ";
Response. Write (Request. Cookies ["User1"]. Values ["UserId"]. ToString ());
Response. Write (Request. Cookies ["User2"]. Values ["UserName"]. ToString ());
Response. Write ("Response. Write (Response. Cookies ["User1"]. Values ["UserId"]. ToString ());
Response. Write (Response. Cookies ["User2"]. Values ["UserName"]. ToString ());
However, once the Cookie exists, the above method is used for reading, and the result is different, Response. cookies can read new Cookies immediately, while requests. the last time Cookies are read, that is, they can only be read when a client sends a request to the server. Why is there such a difference? It should be the issue of. NET implementation, which contains the following section:
C # code
If (includeResponse & (this. Response! = Null ))
{
HttpCookieCollection cookies = this. Response. Cookies;
If (cookies. Count> 0)
{
HttpCookie [] dest = new HttpCookie [cookies. Count];
Cookies. CopyTo (dest, 0 );
For (int I = 0; I <dest. Length; I ++)
{
CookieCollection. AddCookie (dest [I], true );
}
}
}
When the Cookie does not exist, it should be the Cookie in Response. Cookies, so the first time it reads the same, but the reason for reading it later is different.
In addition, Response. Cookies must be read after they are configured. They cannot be read at any time like Request. Cookies. If you read Cookies on other pages, the following method is incorrect.
C # code
Protected void Page_Load (object sender, EventArgs e)
{
Response. Write (Response. Cookies ["User1"]. Values ["UserId"]. ToString ());
Response. Write (Response. Cookies ["User2"]. Values ["UserName"]. ToString ());
}
Author: Meng xianhui