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?
The problem lies in following code:
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 ….
[ More detail in the article ]