Cookie expires in past in asp.net mvc

I write / update a cookie, but every time I do this, and I look at the chrome dev tools, it tells me that the cookie expires 30 minutes ago, not 30 minutes later.

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 is happening?

+4
source share
1 answer

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

Source: https://habr.com/ru/post/1675899/


All Articles