ASP MVC Cookies Not Saved

I have an ASP MVC application with some seemingly simple code to save and retrieve cookies, but for some reason they will not be saved. Code in the controller:

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 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, is cookie always null?

+53
cookies asp.net-mvc
Jan 19 '09 at 7:38
source share
2 answers

The problem is the following code:

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

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

Check out 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 ....

A brief explanation if you do not like to read the whole story

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

[ More in the article ]

+92
Feb 26 '09 at 12:03
source share

In summary, do not use β€œ Response ” to read cookies, use β€œ Request ”.

+1
May 13 '13 at 14:35
source share



All Articles