【问题标题】:How to correctly set expiration datetime for cookies on ASP.NET Core MVC如何在 ASP.NET Core MVC 上正确设置 cookie 的到期日期时间
【发布时间】:2017-02-06 19:32:18
【问题描述】:

我正在尝试从后端(Asp.Net 核心)向浏览器设置一个 Cookie,该 Cookie 应在第二天的同一时间减去 5 分钟后过期。这是来自控制器的 C# 代码

HttpContext.Response.Cookies.Append("MyCookie",
       "test cookie value",
       new Microsoft.AspNetCore.Http.CookieOptions
       {
             Expires = DateTimeOffset.UtcNow.AddDays(1).AddMinutes(-5)
       });

但是对于浏览器来说,过期日期时间是错误的。

例如,如果 cookie 过期日期设置为 2016-09-28 19:15,在浏览器上它将在 2016-09-29T17:15 过期,并且减少了 2 小时,这很奇怪,因为我的时区是 +1。

【问题讨论】:

    标签: c# cookies asp.net-core asp.net-core-mvc


    【解决方案1】:

    DateTimeOffset.UtcNow 是 DateTimeOffset.Now + yourTimezone。

    所以

    DateTimeOffset.UtcNow.AddDays(1).AddMinutes(-5)
    

    将返回相同的

    DateTimeOffset.Now.AddDays(1).AddMinutes(-5).AddHours(-2 /*your Timezone*/)
    

    浏览器显示一切正常。

    把你的代码改成

    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 + 客户的时区

    【讨论】:

    • 我收到此方法错误:无法将类型“System.DateTimeOffset”隐式转换为“System.DateTime”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-23
    • 1970-01-01
    相关资源
    最近更新 更多