ASP MVC Cookie不会持续

我有一个ASP MVC应用程序与一些看似简单的代码来保存和检索cookie,但由于某些原因,他们不会坚持。 控制器中的代码是:

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); } 

并再次加载它:

 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; } 

由于某些原因,Cookie始终为空?

问题在于以下代码:

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

当您尝试使用响应对象而不是请求来检查cookie的存在时,ASP.net会自动创build一个cookie。

检查这个详细的职位在这里: http : //chwe.at/blog/post/2009/01/26/Done28099t-use-ResponseCookiesstring-to-check-if-a-cookie-exists!.aspx


如果链接再次下降,则从文章引用….

简短的解释,如果你不喜欢阅读整个故事

如果你使用“if(Response.Cookies [”mycookie“]!= null){…}”这样的代码,ASP.Net会在后台自动生成一个名为“mycookie”的新cookie,并覆盖旧的cookie! 始终使用Request.Cookies-Collection来读取cookie!

[ 文章中的更多细节 ]

在简历中,不要使用“ 响应 ”来读取cookie,请使用“ 请求 ”。