Bill Jones
Bill Jones

Reputation: 701

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. 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?

Upvotes: 3

Views: 6253

Answers (1)

krajew4
krajew4

Reputation: 839

Look at the Expires property of HttpCookie object - more on this here. I believe you shoud set cookie expiration date in future like in the example on msdn site. Because you set date time in the past the cookie automatically expires and you are never able to read it.

Upvotes: 5

Related Questions