61

Do I use response when at a page event (e.g. load) as this is a response from ASP.NET, and request when pressing a button as this is a response going to ASP.NET for processing? Or is there more to it?

secretformula
  • 6,414
  • 3
  • 33
  • 56
GurdeepS
  • 65,107
  • 109
  • 251
  • 387

6 Answers6

102

They are 2 different things, one SAVES [Response], the other READS [Request]

in a Cookie (informatics speaking) :) you save a small file for a period of time that contains an object of the type string

in the .NET framework you save a cookie doing:

HttpCookie myCookie = new HttpCookie("MyTestCookie");
DateTime now = DateTime.Now;

// Set the cookie value.
myCookie.Value = now.ToString();
// Set the cookie expiration date.
myCookie.Expires = now.AddMinutes(1);

// Add the cookie.
Response.Cookies.Add(myCookie);

Response.Write("<p> The cookie has been written.");

You wrote a cookie that will be available for one minute... normally we do now.AddMonth(1) so you can save a cookie for one entire month.

To retrieve a cookie, you use the Request (you are Requesting), like:

HttpCookie myCookie = Request.Cookies["MyTestCookie"];

// Read the cookie information and display it.
if (myCookie != null)
   Response.Write("<p>"+ myCookie.Name + "<p>"+ myCookie.Value);
else
   Response.Write("not found");

Remember:

To Delete a Cookie, there is no direct code, the trick is to Save the same Cookie Name with an Expiration date that already passed, for example, now.AddMinutes(-1)

this will delete the cookie.

As you can see, every time that the time of life of the cookie expires, that file is deleted from the system automatically.

lionello
  • 499
  • 9
  • 11
balexandre
  • 73,608
  • 45
  • 233
  • 342
  • 7
    +1 I didn't realise you had to re-save the cookie to update the expiry – Andrew Apr 29 '10 at 10:48
  • 1
    This was mostly helpful, but a bit misleading since in your example when you go to retrieve the cookie you actually overwrite the cookie that was previously saved with the line `HttpCookie myCookie = new HttpCookie("MyTestCookie");` Instead use something like `HttpCookie myCookie = new HttpCookie("MyWrittenCookie");` – Off The Gold Nov 14 '13 at 20:16
  • 2
    This doesn't support reading a cookie that has just been sent in the response, in which case you need to use `Response.Cookies` – ajbeaven Oct 13 '15 at 03:27
  • I believe this is true when you are programming Server side code. for client code it is the other way round. – AaA Mar 30 '17 at 08:59
  • Why `Request.Cookies[""].Value` is different compare to what I see _and actually stored_ in the browser? _I checked that value of the cookie using browser console_ – Mehdi Dehghani Dec 19 '19 at 13:18
  • @MehdiDehghani from the browser you can only access browser cookies, not Https or Server cookies, for example, make sure you are reading the correct cookie, [here's some hacks](https://stackoverflow.com/a/8069697/28004) and also, make sure the server isn't overriding that value with something else... – balexandre Dec 19 '19 at 15:08
41

In a web application the request is what comes from the browser and the response is what the server sends back. When validating cookies or cookie data from the browser you should use the Request.Cookies. When you are constructing cookies to be sent to the browser you need to add them to Response.Cookies.

tvanfosson
  • 524,688
  • 99
  • 697
  • 795
  • For clarification, _server_ here means the application processing and responding to the Request from the browser. – Suncat2000 Dec 21 '20 at 13:34
19

When writing a cookie, use Response but reading may depend on your situation. Normally, you read from Request but if your application is attempting to get a cookie that has just been written or updated and the round trip to the browser has not occured, you may need to read it form Response.

I have been using this pattern for a while and it works well for me.

public void WriteCookie(string name, string value)
{
    var cookie = new HttpCookie(name, value);
    HttpContext.Current.Response.Cookies.Set(cookie);
}


public string ReadCookie(string name)
{
    if (HttpContext.Current.Response.Cookies.AllKeys.Contains(name))
    {
        var cookie = HttpContext.Current.Response.Cookies[name];
        return cookie.Value;
    }

    if (HttpContext.Current.Request.Cookies.AllKeys.Contains(name))
    {
        var cookie = HttpContext.Current.Request.Cookies[name];
        return cookie.Value;
    }

    return null;
}
andleer
  • 22,388
  • 8
  • 62
  • 82
  • 4
    An alternate but equal approach would be to simply write your cookie to the Response.Cookies AND Request.Cookies collections when saving. This way, any further logic in the cycle can read the cookie you've just set without looking in the Response object. – Chris Feb 23 '09 at 00:59
  • 1
    Chris, agreed and I used to do that but I recently read that modifying the Request object is a no-no. Will try to find a reference. – andleer Feb 23 '09 at 01:11
  • Thanks, Chris. Andrew--I would love to see that reference. For now I'm going with Chris's solution. – catfood Sep 09 '09 at 19:30
4

The cookies comes from the browser in the Request.Cookies collection. That is where you read the cookies that was sent.

To send cookies back to the browser you put them in the Response.Cookies collection.

If you want to delete a cookie, you have to tell the browser to remove it by sending the cookie with an expiration date that has passed. The browser is using the local time of the client computer so if you are using the server time to create a date, be sure to subtract at least one day to be sure that it has actually passed in the clients local time.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
3

When i create or update a cookie in .NET i normally do it to both the request and response cookie collection. That way you can be sure if you try to read the cookie further down the page request sequence it will have the correct information.

Alex
  • 34,776
  • 10
  • 53
  • 68
  • Alex, this particular issue has been bothering me all day. Thanks for clearing it up so simply! – catfood Sep 09 '09 at 19:29
  • Yeh, there are some interesting behaviors where setting a cookie in Response will also set it in the Request if it didn't already exist. But if it did exist in the Request already, setting Response does NOT update Request. So seems like a feature intended to be helpful, but somewhat inconsistent. Certainly when modifying a cookie mulitiple times in same request you can run into bugs. – AaronLS Jul 09 '14 at 21:31
1

Andrew's Code gave an error in "AllKeys.Contains" Method. So I corrected a little..

public void WriteCookie(string strCookieName, string strCookieValue)
    {
        var hcCookie = new HttpCookie(strCookieName, strCookieValue);
        HttpContext.Current.Response.Cookies.Set(hcCookie);
    }


    public string ReadCookie(string strCookieName)
    {    
        foreach (string strCookie in HttpContext.Current.Response.Cookies.AllKeys)
        {
            if (strCookie == strCookieName)
            {
                return HttpContext.Current.Response.Cookies[strCookie].Value;
            }
        }         

        foreach (string strCookie in HttpContext.Current.Request.Cookies.AllKeys)
        {
            if (strCookie == strCookieName)
            {
                return HttpContext.Current.Request.Cookies[strCookie].Value;
            }
        }

        return null;
    }
Community
  • 1
  • 1
Venkatx5
  • 11
  • 1