Craig
Craig

Reputation: 36816

ASP MVC Cookies not persisting

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?

Upvotes: 56

Views: 30482

Answers (2)

Fernando JS
Fernando JS

Reputation: 4317

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

Upvotes: 2

Nilesh Deshpande
Nilesh Deshpande

Reputation:

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 ]

Upvotes: 98

Related Questions