Asp.net ASP MVC Cookie未持久化
我有一个ASP MVC应用程序,其中包含一些看似简单的代码来保存和检索cookies,但由于某些原因,它们不会持久存在。控制器中的代码为:Asp.net ASP MVC Cookie未持久化,asp.net,asp.net-mvc,cookies,Asp.net,Asp.net Mvc,Cookies,我有一个ASP MVC应用程序,其中包含一些看似简单的代码来保存和检索cookies,但由于某些原因,它们不会持久存在。控制器中的代码为: if (System.Web.HttpContext.Current.Response.Cookies["CountryPreference"] == null) { HttpCookie cookie = new HttpCookie("CountryPreference"); cookie.Value = country; coo
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)
当您尝试使用响应对象而不是请求检查cookie是否存在时,ASP.net会自动创建cookie
请在此处查看此详细帖子:
引用文章中的内容,以防链接再次中断 简短的解释,如果你不知道的话 我喜欢读整个故事 如果您使用类似“If”的代码 (Response.Cookies[“mycookie”!=null) {…}”,ASP.Net自动运行 生成名为的新cookie 背景中的“mycookie”和 覆盖你的旧饼干!始终使用 要读取的Request.Cookies-Collection 饼干
[]在简历中,不要使用“响应””读取cookies,请使用“请求””.当你用FireBug或类似的东西检查请求和响应时,cookie是否存在?我早就知道了,但我不得不说这是微软在.NET中做过的最愚蠢的API决定之一。iv'e也遇到了同样的问题,我只使用请求来读取cookie,我知道在这种情况下使用请求而不是响应比使用请求更好创建一个cookie,但由于某些原因,在获取cookie时,我必须复制并粘贴它,并将其保留为响应-因此我的cookie不会持续超过第一页加载。谢谢你!隐马尔可夫模型。。。是否可以使用此行为故意删除现有cookie?