1

I want to set a cookie that "never" expires, which means setting it to 2^31 - 1 which is an absolute value/date rather than an offset, to avoid the 2038 wrap-around bug.

To set a cookie in ASP.NET Core:

Response.Cookies.Append("name", "value", new CookieOptions() { /*...*/ })

I can't use DateTime.MaxValue and so on due to the bug. What should I use for CookieOptions?

lonix
  • 14,255
  • 23
  • 85
  • 176
  • 2
    The site you're building nor the machine you're wanting to set the cookie on will be around in twenty years from now. – CodeCaster Jul 26 '18 at 10:22
  • 1
    @CodeCaster I know, but I'd like to know how to do this regardless. We have a system in our server room that apparently has been running for over 25 years (cobol), so yeah. :-) – lonix Jul 26 '18 at 10:24

1 Answers1

1

I decided to hardcode the value like this:

var co = new CookieOptions();
co.Expires = new DateTimeOffset(2038, 1, 1, 0, 0, 0, TimeSpan.FromHours(0));

That avoids the 2038 problem.

lonix
  • 14,255
  • 23
  • 85
  • 176
  • 2
    This code doesn't avoid it. In fact it makes sure the 2038 problem will still exist in the code even when underlying protocols have already fixed it. A quick calculation tells me that I'll be working until 2047 so I just can't leave it like this, any other solutions? :) – huysentruitw Jan 02 '19 at 12:22
  • @Housy Been a while since I looked at this code - what it wrong with it? If you have a better solution, post it and I'll mark yours as correct. – lonix Jan 02 '19 at 17:02
  • The problem is that it will stop working at 2 January 2038. I wonder if adding 20 years to the current time is problematic for all recent browsers. Might have to test this if I find the time. – huysentruitw Jan 03 '19 at 09:30
  • @Housy Oh I see what you mean - well everyone considers 2038 as a hard reality, so I just worked around it. Would be nice not to deal with it at all, but I doubt that's possible without some hackery. Update me if you think of something. – lonix Jan 03 '19 at 11:07
  • 1
    Even Google uses 2038 as max-age for cookies. I just checked google.com in my browser: https://i.imgur.com/6qXbiDA.png – Bruno Cassol Jun 04 '21 at 02:40
  • 1
    @BrunoCassol Good to know, thanks. Interesting / scary that's it's the consent cookie that lives "forever"... "Here, take my info, yes *of course* you can keep it forever!" :-) :-( – lonix Jun 04 '21 at 07:52
  • 1
    Chrome as of January 12th, 2023 set a max cap limit for the days to 400 days. No cookie can have an expiration date of over 400 days. As Chrome will cap at 400 days regards. Article - https://developer.chrome.com/blog/cookie-max-age-expires/ – TechLoom Jun 19 '23 at 01:08