asp.net - ASP MVC Cookie 不持久

标签 asp.net asp.net-mvc cookies

我有一个 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。

在此处查看此详细帖子:http://chwe.at/blog/post/2009/01/26/Done28099t-use-ResponseCookiesstring-to-check-if-a-cookie-exists!.aspx

<小时/>

引用文章,以防链接再次失效......

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!

[More detail in the article ]

关于asp.net - ASP MVC Cookie 不持久,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/456807/

相关文章:

asp.net-mvc - 一个 html 元素中的多个 CSS 类 ASP.NET MVC 3

c# - System.Web.Optimization错误添加

cookies - 一些迭代后 Jmeter 清除 cookie

java - 访问 REST Web 服务的摘要式身份验证

ASP.Net Web API - 从 ASP.NET MVC 项目生成 Bearer Token

asp.net - 使用 ASP.NET MVC 时未触发 FormsAuthenticationModule 身份验证事件

jquery - 将所选内容应用于 jtable 多选下拉列表

angularjs - 在 Spring Security 或 Angular 中注销时清除 Cookie

c# - 如何在 asp.net 应用程序中从 jquery 设置 HttpPost 端点

c# - 如何通过命名空间限制 Asp.net Web API/Owin 发现 Controller ?