这似乎应该很简单。但是,对于我的生活,我似乎无法在 ASP.NET MVC 中创建 cookie。目前,我有以下代码:
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);
}
我设置了一个断点,并注意到似乎正在添加 cookie。(是的,我正在进入Request.Browser.Cookies
街区)。然后我尝试使用以下方法检索 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;
}
}
不幸的是,lastActivityCookie
总是null
。此外,当我在 Chrome 中查看“资源”选项卡时,我看到了 cookie 分支,但是,我尝试创建的 cookie 没有列出。不过,还列出了另外两个 cookie,包括 .ASPXAUTH cookie。我究竟做错了什么?