我有一个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总是空的?
发布于 2009-02-26 12:03:18
问题出在以下代码中:
if (System.Web.HttpContext.Current.Response.Cookies["CountryPreference"] == null)
当您尝试使用Response object而不是Request检查cookie是否存在时,ASP.net会自动创建cookie。
引用这篇文章中的话以防链接再次中断...
简短的解释,如果你不喜欢读整个故事
如果使用类似“If (Response.Cookies”mycookie“!= null) {…){null}“,ASP.Net会在后台自动生成一个名为”mycookie“的新cookie,并覆盖您的旧cookie!始终使用Request.Cookies-Collection来读取cookies!
发布于 2013-05-13 22:35:38
在简历中,不要使用"Response“来读取cookie,请使用"Request”。
https://stackoverflow.com/questions/456807
复制相似问题