24

I just want to clear this up.

I know that if I have set a cookie on a previous request, it will show up in my Request.Cookies collection.

I want to update my existing Cookie.

Are the cookies from my Request.Cookies collection already copied to my Response.Cookies collection? Do I need to add a new cookie with the same key using Response.Cookies.Add(), or do I need to use Response.Cookies.Set()?

smartcaveman
  • 41,281
  • 29
  • 127
  • 212

1 Answers1

30

There is a difference:

Duplicate cookies typically requires extra handling to determine which is the most recent. I'm not sure of a case when you would want duplicate cookies on the same site, maybe someone else can chime in with an example

Edit: In your case, you want to use set because you are updating.

Prescott
  • 7,312
  • 5
  • 49
  • 70
  • 3
    Thanks - I also did some reflection and I realized I am asking the wrong question. Please check out this post: http://stackoverflow.com/questions/5517595/what-is-the-best-practice-for-updating-a-cookie-that-was-set-on-a-previous-reques – smartcaveman Apr 01 '11 at 18:54
  • 3
    this is badly documented. the [original documentation](https://msdn.microsoft.com/en-us/library/system.web.httpcookiecollection.set(v=vs.110).aspx) includes the statement "Updates the value of an **existing** cookie in a cookie collection" which is just wrong because if the cookie does not exist, it is added. the [underlying code](https://referencesource.microsoft.com/#System.Web/HttpCookieCollection.cs,98) uses a `BaseAdd` call which updates existing keys and adds new keys. – Cee McSharpface Jun 03 '18 at 13:30
  • I don't think one can have the confidence that code the document refers to in 2011 is the same code you have linked to that is 4.7.2. – Prescott Jun 05 '18 at 07:49