I'm trying to set a Cookie to the browser from back-end (Asp.Net core) which should expire on the next day same time minus 5 minutes. Here is the C# code from controller
HttpContext.Response.Cookies.Append("MyCookie",
"test cookie value",
new Microsoft.AspNetCore.Http.CookieOptions
{
Expires = DateTimeOffset.UtcNow.AddDays(1).AddMinutes(-5)
});
But to the browser it is coming with wrong expiration DateTime.
For example if cookie expiration date was set to 2016-09-28 19:15, on the browser it will expire at 2016-09-29T17:15, and it is 2 hours less, which is weird because my time zone is +1.
Set an expiration date for a cookie This can be done easily by adding expires=expirationDate in UTC separated by semicolon from the name=value, as seen in the following example: document. cookie = "username=Max Brown; expires=Wed, 05 Aug 2020 23:00:00 UTC"; document.
The default time for a Cookie to expire is 30 minutes. The default Expires value for a cookie is not a static time, but it creates a Session cookie. This will stay active until the user closes their browser/clears their cookies. You can override this as required.
If a cookie is valid and can be read by the domain, it will be passed along with the HTTP request to the domain that it originated from. If you want a cookie to expire at a specific time, you need to set an expiration date.
The Kind property of Expires is used to determine if the cookie is set to DateTimeKind.
DateTimeOffset.UtcNow is DateTimeOffset.Now + yourTimezone.
So
DateTimeOffset.UtcNow.AddDays(1).AddMinutes(-5)
Will return the same as
DateTimeOffset.Now.AddDays(1).AddMinutes(-5).AddHours(-2 /*your Timezone*/)
Browser showed everything right.
Change your code to
HttpContext.Response.Cookies.Append("MyCookie",
"test cookie value",
new Microsoft.AspNetCore.Http.CookieOptions
{
Expires = DateTimeOffset.Now.AddDays(1).AddMinutes(-5)
});
//if you want to have the same expiration date as your server's
or use UtcNow + client's timezone
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With