56

I have a ASP MVC App with some seemingly simple code to save and retrieve cookies but for some reason they won't persist. The code in the controller is :

if (System.Web.HttpContext.Current.Response.Cookies["CountryPreference"] == null)
{
    HttpCookie cookie = new HttpCookie("CountryPreference");
    cookie.Value = country;
    cookie.Expires = DateTime.Now.AddYears(1);
    System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
}

And to load it again :

if (System.Web.HttpContext.Current.Request.Cookies["CountryPreference"] != null)
{
    System.Web.HttpContext.Current.Request.Cookies["CountryPreference"].Expires = DateTime.Now.AddYears(1);
    data.Country = System.Web.HttpContext.Current.Request.Cookies["CountryPreference"].Value;
}

For some reason the cookie is always null?

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
Craig
  • 36,306
  • 34
  • 114
  • 197

2 Answers2

98

The problem lies in following code:

if (System.Web.HttpContext.Current.Response.Cookies["CountryPreference"] == null)

When you try to check existence of a cookie using Response object rather than Request, ASP.net automatically creates a cookie.

Check this detailed post here: http://chwe.at/blog/post/2009/01/26/Done28099t-use-ResponseCookiesstring-to-check-if-a-cookie-exists!.aspx


Quote from the article in case the link goes down again ....

The short explanation, if you don’t like to read the entire story

If you use code like “if (Response.Cookies[“mycookie”] != null) { … }”, ASP.Net automatically generates a new cookie with the name “mycookie” in the background and overwrites your old cookie! Always use the Request.Cookies-Collection to read cookies!

[ More detail in the article ]

John K
  • 28,441
  • 31
  • 139
  • 229
  • 9
    I +1'd this a long time ago but I have to say this was one of the most asinine API decisions ever done by Microsoft in .NET. – Chris Marisic Aug 04 '11 at 12:14
  • 2
    iv'e got the same problem and i only use request to read cookies http://stackoverflow.com/questions/7510327/cookie-values-disappear-when-page-re-loads – eran otzap Sep 22 '11 at 06:52
  • 2
    I know better than to use request instead of response when CREATING a cookie, but for some reason when GETTING it I must of copied and pasted and left it as response - so my cookies weren't persisting past the first page load. Thanks for this! – Losbear Mar 22 '13 at 13:57
  • 1
    Hmm... could this behavior be used to intentionally delete an existing cookie? – AbeyMarquez Aug 02 '18 at 22:32
2

In resume, don't use "Response" to read cookies, use "Request".

Fernando JS
  • 4,267
  • 3
  • 31
  • 29