2016-09-28 94 views
2

我想從後端(Asp.Net核心)設置一個Cookie到瀏覽器,它應該在第二天同時減去5分鐘。這裏是來自控制器的C#代碼如何正確設置ASP.NET核心上的Cookie的展開日期時間MVC

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小時,這很奇怪,因爲我的TimeZone是+1。

回答

2

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 +客戶端的時區