简体   繁体   English

我的cookie什么时候会过期?

[英]When will my cookie actually expire?

I have an ASP.NET application running on a server in California. 我在加利福尼亚州的服务器上运行了一个ASP.NET应用程序。 The server's current time is: 服务器的当前时间是:

  • 7/20/2015 14:00 UTC-08:00 7/20/2015 14:00 UTC-08:00

Bob is connected to my server. Bob已连接到我的服务器。 Bob is in Texas. 鲍勃在德克萨斯州。 His current time is: 他现在的时间是:

  • 7/20/2015 16:00 UTC-06:00 7/20/2015 16:00 UTC-06:00

My application creates a cookie and set its expiration date. 我的应用程序创建一个cookie并设置其到期日期。

var name = "MyName";
var value = "MyValue"
var hoursToLive = 24;

var myCookie = new HttpCookie(name )
{
    Value = value,
    Expires = DateTime.Now.AddHours(hoursToLive)
};

Will the cookie expire in 24 hours, or will it expire in 22 hours due to the time difference between Bob and the server? 由于Bob和服务器之间的时差,cookie会在24小时后到期,还是会在22小时后到期? I know that DateTime.Now uses the server's local time , but I am unclear as to how browsers decide that a cookie is expired (specifically, what time zone is used to determine expiration). 我知道DateTime.Now使用服务器的本地时间 ,但我不清楚浏览器如何确定cookie过期(具体来说,用什么时区来确定过期时间)。

Cookies do include a timezone information with the expires header (mostly GMT), which makes it quite simple for the client to cope with the offset to the server's actual timezone. Cookie包含带有expires标头的时区信息(主要是GMT),这使得客户端可以非常简单地处理服务器实际时区的偏移量。

Example: expires=Mon,20-Jul-2015 22:00:00 GMT if 2015-07-20 14:00:00 UTC-8 is the server's time. 示例: expires=Mon,20-Jul-2015 22:00:00 GMT如果2015-07-20 14:00:00 UTC-8是服务器的时间。 When the client or server decides whether the cookie is expired or not, it will compare it to the associated GMT time. 当客户端或服务器决定cookie是否过期时,它会将其与相关的GMT时间进行比较。

I dug deeper into the code of System.Web.HttpCookie , and found the relevant code in GetSetCookieHeader() : 我深入研究了System.Web.HttpCookie的代码,并在GetSetCookieHeader()找到了相关的代码:

        if (_expirationSet && _expires != DateTime.MinValue) {
            s.Append("; expires=");
            s.Append(HttpUtility.FormatHttpCookieDateTime(_expires));
        }

Where HttpUtility.FormatHttpCookieDateTime() returns a UTC timestamp (with no offset, which doesn't matter because the offset would be zero). 其中HttpUtility.FormatHttpCookieDateTime()返回UTC时间戳(没有偏移量,这无关紧要,因为偏移量为零)。

Greenwich Mean Time (GMT) and Coordinated Universal Time (UTC) can, for most purposes, be considered the same. 对于大多数目的,格林威治标准时间(GMT)和协调世界时(UTC)可以被认为是相同的。 You can read more about this here . 你可以在这里阅读更多相关信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM