简体   繁体   English

在ASP.NET MVC中创建Cookie

[英]Creating a Cookie in ASP.NET MVC

This seems like it should be pretty straightforward. 这看起来应该非常简单。 However, for the life of me, I can't seem to create a cookie in ASP.NET MVC. 但是,对于我的生活,我似乎无法在ASP.NET MVC中创建一个cookie。 Currently, I have the following code: 目前,我有以下代码:

DateTime lastActivityDate = DateTime.UtcNow;
if (Request.Browser.Cookies)
{
  HttpCookie lastActivityCookie = new HttpCookie(COOKIE_LAST_ACTIVITY, lastActivityDate.ToShortDateString());
  lastActivityCookie.Expires = DateTime.Now.AddMonths(-12);                    
  this.ControllerContext.HttpContext.Response.Cookies.Add(lastActivityCookie);
}

I've set a breakpoint and noticed that the cookie appears to be getting added. 我设置了一个断点,注意到cookie似乎被添加了。 (yes, I'm getting into the Request.Browser.Cookies block). (是的,我正在进入Request.Browser.Cookies块)。 I then attempt to retrieve the cookie using the following: 然后我尝试使用以下方法检索cookie:

DateTime lastActivity = DateTime.UtcNow.AddDays(-7);        // Default to the past week

HttpCookie lastActivityCookie = Request.Cookies[COOKIE_LAST_ACTIVITY];
if (lastActivityCookie != null)
{
  DateTime temp = DateTime.UtcNow;
  if (String.IsNullOrWhiteSpace(lastActivityCookie.Value) == false)
  {
    if (DateTime.TryParse(lastActivityCookie.Value, out temp))
      lastActivity = temp;
  }
}

Unfortunately, lastActivityCookie is always null . 不幸的是, lastActivityCookie始终为null In addition, when I look in the "Resources" tab in Chrome, I see the cookies branch, however, the cookie I'm trying to create is not listed. 此外,当我查看Chrome中的“资源”选项卡时,我会看到cookie分支,但是,我正在尝试创建的cookie未列出。 There are two other cookies listed though, including the .ASPXAUTH cookie. 但是列出了另外两个cookie,包括.ASPXAUTH cookie。 What am I doing wrong? 我究竟做错了什么?

Look at the Expires property of HttpCookie object - more on this here . 查看HttpCookie对象的Expires属性 - 更多内容在此处 I believe you shoud set cookie expiration date in future like in the example on msdn site. 我相信你将来会像在msdn网站上的例子一样设置cookie到期日期。 Because you set date time in the past the cookie automatically expires and you are never able to read it. 因为您在过去设置了日期时间,所以Cookie会自动过期,您永远无法读取它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM