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. 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. (yes, I'm getting into the Request.Browser.Cookies block). I then attempt to retrieve the cookie using the following:
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. 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. There are two other cookies listed though, including the .ASPXAUTH cookie. What am I doing wrong?