如何在ASP.NET Core MVC上正确设置Cookie的展示日期时间 [英] How to correctly set exparation datetime for cookies on ASP.NET Core MVC
问题描述
我正在尝试从后端(Asp.Net核心)向浏览器设置Cookie,该Cookie应该在第二天的同一时间减去5分钟后过期.这是来自控制器
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.
例如,如果Cookie的到期日期设置为2016-09-28 19:15,则在浏览器上它将在2016-09-29T17:15到期,并且少了2个小时,这很奇怪,因为我的TimeZone是+1.
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.
推荐答案
DateTimeOffset.UtcNow是DateTimeOffset.Now + yourTimezone.
DateTimeOffset.UtcNow is DateTimeOffset.Now + yourTimezone.
所以
DateTimeOffset.UtcNow.AddDays(1).AddMinutes(-5)
将返回与
DateTimeOffset.Now.AddDays(1).AddMinutes(-5).AddHours(-2 /*your Timezone*/)
浏览器显示一切正常.
Browser showed everything right.
将代码更改为
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
或使用UtcNow +客户的时区
or use UtcNow + client's timezone
这篇关于如何在ASP.NET Core MVC上正确设置Cookie的展示日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!