gpt4 book ai didi

asp.net - ASP MVC Cookie 不持久

转载 作者:行者123 更新时间:2023-12-03 05:54:02 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com