ASP MVC Cookie不持续 [英] ASP MVC Cookies not persisting

查看:140
本文介绍了ASP MVC Cookie不持续的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP MVC应用程序与一些看似简单的代码来保存和检索Cookie,但由于某种原因,他们不会持久。控制器中的代码是:

I have a ASP MVC App with some seemingly simple code to save and retrieve cookies but for some reason they won't persist. The code in the controller is :

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总是空的?

For some reason the cookie is always null?

推荐答案

问题出在以下代码中:

if (System.Web.HttpContext.Current.Response.Cookies["CountryPreference"] == null)

当您尝试使用Response对象而不是请求检查cookie的存在时,ASP.net自动创建一个cookie。

When you try to check existence of a cookie using Response object rather than Request, ASP.net automatically creates a cookie.

请在这里查看详细的文章: http://chwe.at/blog/post/2009/01/26/Done28099t-use-ResponseCookiesstring-to-check- if-a-cookie-exists!.aspx

Check this detailed post here: http://chwe.at/blog/post/2009/01/26/Done28099t-use-ResponseCookiesstring-to-check-if-a-cookie-exists!.aspx

如果链接失效,再次....

Quote from the article in case the link goes down again ....


简短的解释,如果你不是
喜欢读整个故事

The short explanation, if you don’t like to read the entire story

如果你使用像if
(Response.Cookies [mycookie]!= null)
{...},ASP.Net自动
在后台生成一个名为
mycookie的新cookie,
覆盖旧的cookie!始终使用
Request.Cookies-Collection读取
cookie!

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 MVC Cookie不持续的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆