Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 836
Franky_frankly Avatar asked Sep 28 '16 17:09

Franky_frankly


People also ask

How do you set the expiration date on cookies?

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.

What is the default cookie expire time in ASP Net?

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.

Is it necessary to write expiry date in cookies in asp net?

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.

Which property is used to set expire date for cookie?

The Kind property of Expires is used to determine if the cookie is set to DateTimeKind.


1 Answers

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

like image 167
Lokki Avatar answered Oct 17 '22 00:10

Lokki