ASP MVC Cookies not persisting

asp.netasp.net MvcCookies

asp.net Problem Overview


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?

asp.net Solutions


Solution 1 - asp.net

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 ]

Solution 2 - asp.net

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCraigView Question on Stackoverflow
Solution 1 - asp.netNilesh DeshpandeView Answer on Stackoverflow
Solution 2 - asp.netFernando JSView Answer on Stackoverflow