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?

1
  • Is the cookie there when you inspect the request & response with FireBug or something like that? Commented Jan 20, 2009 at 9:46

2 Answers 2

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 ]

Sign up to request clarification or add additional context in comments.

4 Comments

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.
iv'e got the same problem and i only use request to read cookies stackoverflow.com/questions/7510327/…
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!
Hmm... could this behavior be used to intentionally delete an existing cookie?
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.