由于以下行为,我刚刚花了半天时间追踪一个错误:-
假设有 不是 在 Http 请求或响应的 cookie 集合中称为“foo”的 cookie。以下代码返回 null
A) HttpContext.Current.Request.Cookies["foo"]
以下代码创建一个名为“foo”的新 cookie(带有 path="/"和空白值),将其添加到响应的 cookie 集合中并返回
B) HttpContext.Current.Response.Cookies["foo"]
所以 (B) 的副作用是任何预先存在的名为“foo”的 cookie 都会在客户端的浏览器上被覆盖。
这不是错误。实际上有人故意编码。这是 Get 方法的反汇编(Item[string name] 索引器委托(delegate)给此方法。
public HttpCookie Get(String name) {
HttpCookie cookie = (HttpCookie)BaseGet(name);
if (cookie == null && _response != null) {
// response cookies are created on demand
cookie = new HttpCookie(name);
AddCookie(cookie, true);
_response.OnCookieAdd(cookie);
}
return cookie;
}
显然 MSDN 文档没有提到这种行为(尽管一些用户在描述这种行为的文档底部添加了评论)。
我的问题是有人可以向我解释为什么
HttpCookieCollection
类有这种行为。
最佳答案
来自 MSDN 文档关于 HttpCookieCollection.Get 方法:http://msdn.microsoft.com/en-us/library/ezy11xy2.aspx
If the named cookie does not exist, this method creates a new cookie with that name.
所以是的,这是故意的。
关于asp.net - 为什么 HttpContext.Response.Cookies ["foo"] 添加一个cookie?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8491075/