ASP MVC Cookies不会持续存在

Cra*_*aig 54 asp.net cookies asp.net-mvc

我有一个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);
}
Run Code Online (Sandbox Code Playgroud)

并再次加载它:

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;
}
Run Code Online (Sandbox Code Playgroud)

由于某种原因,cookie总是为空?

小智 94

问题出在以下代码中:

if (System.Web.HttpContext.Current.Response.Cookies["CountryPreference"] == null)
Run Code Online (Sandbox Code Playgroud)

当您尝试使用Response对象而不是Request来检查cookie的存在时,ASP.net会自动创建一个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!

[ 文章中的更多细节 ]

  • 我很久以前就已经给过这个,但我不得不说这是微软在.NET中做过的最愚蠢的API决定之一. (8认同)
  • 我遇到了同样的问题,我只使用请求来读取 cookie http://stackoverflow.com/questions/7510327/cookie-values-disappear-when-page-re-loads (2认同)
  • 我知道在创建cookie时使用请求而不是响应更好,但出于某种原因,在获取它时我必须复制并粘贴并将其作为响应 - 所以我的cookie不会持续超过第一页加载.谢谢你! (2认同)