简体   繁体   中英

Cookie expiration date not working C#

I'm setting a cookie like so:

protected void SetCookie(bool value, int expiration)
{
    var cookie = Response.Cookies[COOKIE_NAME] ?? new HttpCookie(COOKIE_NAME);
    cookie.Value = value.ToString();
    cookie.Expires = DateTime.UtcNow.AddDays(expiration);
    Response.Cookies.Set(cookie);
}

In the SetCookie function, when I inspect the cookie on the last line, the Expiration is set to tomorrow's date.

However, when I retrieve this cookie on the next page load:

var cookie = Request.Cookies[COOKIE_NAME];

the cookie exists, but the expiration date is the default date value of 1/1/0001 12:00:00 AM

I believe the expiration is a client-side thing. The browser should send any not-expired cookies, but does not send the expiration date (only name and value). I think you should re-set and refresh the expiration on each request.

This was the first format reference I found: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cookie

If for whatever reason you need to retrieve the expiration data server side, I would include it in the cookie contents or set a secondary cookie to contain that information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM