Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does HttpContext.Response.Cookies["foo"] add a cookie?

Tags:

asp.net

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.

like image 392
Chris Fewtrell Avatar asked Dec 13 '11 14:12

Chris Fewtrell


2 Answers

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.

like image 101
Vincent de Lagabbe Avatar answered Oct 06 '22 04:10

Vincent de Lagabbe


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.

like image 43
blowdart Avatar answered Oct 06 '22 05:10

blowdart