Lex
Lex

Reputation: 891

Cookie expire date in the past in asp.net mvc

I'm writing/updating a cookie, however every time I do this and I look at the chrome dev tools, it tells me the cookie expires 30 minutes ago, not 30 minutes from now.

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);

Does anyone know why this happens?

Upvotes: 4

Views: 3056

Answers (2)

simon at rcl
simon at rcl

Reputation: 7344

What time zone are you in? If for instance you're in UTC - 1 then:

  • Current local time is 12:00
  • UTC time is 13:00
  • cookie expires 12:30 (since you're not using UtcNow)
  • Browser may think 12:30 is UTC time and thus is the past.

This is kinda-sorta plausible, so take it with a large pinch of salt!

Upvotes: 1

Ashiquzzaman
Ashiquzzaman

Reputation: 5284

Try:

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);

OR

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);
}

Upvotes: 0

Related Questions