Cookie在asp.net mvc中过期

时间:2017-04-28 10:20:26

标签: asp.net asp.net-mvc cookies http-headers

我正在编写/更新cookie,但是每次我执行此操作并查看chrome dev工具时,它会告诉我Cookie会在30分钟前到期,而不是30分钟后到期。

HttpCookie cookie;

if (Request.Cookies.AllKeys.Contains(name))
{
  cookie = Request.Cookies[name];
}
else
{
  cookie = new HttpCookie(name);
}

cookie.Value = value;
cookie.Expires = DateTime.Now.AddMinutes(30);
Response.Cookies.SetCookie(cookie);

有谁知道为什么会这样?

2 个答案:

答案 0 :(得分:0)

尝试:

var response = HttpContext.Current.Response;
if (Request.Cookies.AllKeys.Contains(name))
{
  response.Cookies.Remove(name);
}

HttpCookie cookie = new HttpCookie(name);
cookie.Value = value;
cookie.Expires = DateTime.Now.AddMinutes(30);
response.Cookies.Add(cookie);

if (Request.Cookies.AllKeys.Contains(name) && Request.Cookies[name]!=null)
{
  var cookie = Request.Cookies[name];
  cookie.Value = value;
  cookie.Expires = DateTime.Now.AddMinutes(30);
  Response.Cookies.Set(cookie);//To update a cookie, you need only to set the cookie again using the new values and also you must include all of the data you want to retain.
}
else
{
  var cookie = new HttpCookie(name);
  cookie.Value = value;
  cookie.Expires = DateTime.Now.AddMinutes(30);
  Response.Cookies.Add(cookie);
}

答案 1 :(得分:0)

您处于哪个时区?例如,如果您使用的是UTC-1,那么:

  • 当前本地时间是12:00
  • UTC时间是13:00
  • Cookie将在12:30过期(因为您没有使用UtcNow)
  • 浏览器可能会认为12:30是UTC时间,因此过去已经是过去了。

这有点像是合理的,所以要带一点点盐!