I have just spent half a day tracking down a bug due to the following behaviour: -
Imagine that there is not a cookie called "foo" in either the Http request's or response's cookie collections. The following code returns null
A) HttpContext.Current.Request.Cookies["foo"]
The following code creates a new cookie called "foo" (with path="/" and blank value), adds it to the response's cookie collection and returns that
B) HttpContext.Current.Response.Cookies["foo"]
So (B) has the side effect that any pre-existing cookie called "foo" is overwritten on the client's browser.
This is not a bug. Someone actually coded this deliberately. Here is the disassembly of the Get method (the Item[string name] indexer delegates to this method.
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;
}
Obviously the MSDN docs do not mention this behaviour (although some users have added comments at the bottom of the docs that describe this behaviour).
My question is can someone explain to me the rational why the HttpCookieCollection
class has this behaviour.
From MSDN doc about HttpCookieCollection.Get method: 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.
So yes, this is done on purpose.
Why? At a guess because it makes sense. If you're doing anything with the response the typical use case is that you want things to be sent to the browser.
You check for values inbound (Request.Cookies) and then you set them outbound (Response.Cookies). The Request is a READ, the Response is a WRITE.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With