HttpCookie

参考 : http://www.cnblogs.com/fish-li/archive/2011/07/03/2096903.html

上文结尾有提到一个说法

4. HttpRequest.Cookies 与 HttpResponse.Cookies 会有关系(很奇怪吧)。

微软官网也是这么说的 : https://msdn.microsoft.com/en-us/library/system.web.httprequest.cookies(v=vs.110).aspx

After you add a cookie by using the HttpResponse.Cookies collection, the cookie is immediately available in theHttpRequest.Cookies collection, even if the response has not been sent to the client.

这情况有时候会让我们有点混淆。所以我特别写了一篇来解释它.

首先我们要知道 

1.

var listx = Response.Cookies.AllKeys.ToList();  //empty list
if (Response.Cookies["c"] != null)
{ 
                                
}
var list = Response.Cookies.AllKeys.ToList(); //["c"] got 1 data 

即使我们只是读取,也是再创建 

2. httpRequest.cookie 的 expires 永远是 0001 年

 Response.Cookies["c"].Expires.Year == 1

回到真题

所以如果说我们想获取某些请求的cookie,我们可以使用 httpRequest.cookie['a'] 去拿,这时你当然有可能也会把response的一起拿出来, 这时我们需要过滤 

如果cookie.expires.year == 1 就表示他是request 而不是response, 除非你的response 也是year == 1 , ... 这哪里可能=.=" 

那么如果我们想要拿一个response则相反,我们去httpResponse拿,然后过滤 year != 1; 

当你的request和response 同时拥有一个同名的cookie时,你使用 request.cookie 和response.cookie 拿出来的cookie是不同的。

说的有点含糊,但是基本上测试一下就明白了。以后有空才写整齐版本.

原文地址:https://www.cnblogs.com/keatkeat/p/4881429.html