Reputation: 891
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
Reputation: 7344
What time zone are you in? If for instance you're in UTC - 1 then:
This is kinda-sorta plausible, so take it with a large pinch of salt!
Upvotes: 1
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