Franky_frankly Franky_frankly - 2 months ago 11
C# Question

How to correctly set exparation datetime for cookies on ASP.NET MVC6 Core

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 TimeZone is +1.

Answer

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