我有一个 ASP MVC 应用程序,其中包含一些看似简单的代码来保存和检索 cookie,但由于某种原因它们不会持久存在。 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);
}
并再次加载它:
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)
当您尝试使用 Response 对象而不是 Request 来检查 cookie 是否存在时,ASP.net 会自动创建一个 cookie。
<小时/>引用文章,以防链接再次失效......
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!
关于asp.net - ASP MVC Cookie 不持久,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/456807/