我的Cookie何时真正过期? [英] When will my cookie actually expire?

查看:90
本文介绍了我的Cookie何时真正过期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在加利福尼亚的服务器上运行着一个ASP.NET应用程序。服务器的当前时间是:

I have an ASP.NET application running on a server in California. The server's current time is:


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

Bob已连接到我的服务器。鲍勃在德克萨斯州。他当前的时间是:

Bob is connected to my server. Bob is in Texas. His current time is:


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

我的应用程序创建一个cookie并设置其过期日期。

My application creates a cookie and set its expiration date.

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

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

该Cookie会在24小时后过期,还是会在22小时后过期(由于两者之间的时间差)鲍勃和服务器?我知道 DateTime.Now使用服务器的本地时间,但是我不清楚浏览器如何确定Cookie过期(具体来说,使用哪个时区来确定到期时间。)

Will the cookie expire in 24 hours, or will it expire in 22 hours due to the time difference between Bob and the server? 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).

推荐答案

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.

示例:如果 2015-07-20 14:00:00 UTC-8, expires =星期一,2015年7月20日22:00:00 GMT 是服务器的时间。当客户端或服务器决定Cookie是否过期时,它将与相关的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. When the client or server decides whether the cookie is expired or not, it will compare it to the associated GMT time.

我更深入地研究了 System.Web.HttpCookie ,以及在 GetSetCookieHeader()中找到了相关代码:

I dug deeper into the code of System.Web.HttpCookie, and found the relevant code in GetSetCookieHeader():

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

其中 HttpUtility.FormatHttpCookieDateTime() 返回UTC时间戳(不包含偏移量,

Where HttpUtility.FormatHttpCookieDateTime() returns a UTC timestamp (with no offset, which doesn't matter because the offset would be zero).

在大多数情况下,格林威治标准时间(GMT)和世界协调时间(UTC)可以认为是相同的。您可以在此处了解更多信息。

Greenwich Mean Time (GMT) and Coordinated Universal Time (UTC) can, for most purposes, be considered the same. You can read more about this here.

这篇关于我的Cookie何时真正过期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆