没有更新过期的ASP.NET Cookie更新值?

时间:2010-04-22 19:15:32

标签: asp.net cookies

是否可以更新ASP.NET Cookie值而无需更新到期时间?我发现,如果我尝试更新Cookie而不更新过期,则该cookie不再存在。我有以下代码,我试图修改。如果每次更新cookie值,到期时有什么意义?

        HttpCookie cookie = HttpContext.Current.Request.Cookies[constantCookie];

        if (cookie == null)
            cookie = new HttpCookie(constantCookie);

        cookie.Expires = DateTime.Now.AddYears(1);
        cookie.Value = openClose;
        HttpContext.Current.Response.Cookies.Set(cookie);

1 个答案:

答案 0 :(得分:5)

ASP.NET HttpCookie类在从HTTP请求读取cookie时无法初始化Expires属性(因为HTTP规范不要求客户端甚至首先将Expiration值发送到服务器)。如果在将HTTP设置回HTTP响应之前没有设置Expires属性,则将其转换为会话cookie而不是持久cookie。

如果你真的必须保持过期,那么你可以将初始过期日期设置为cookie值的一部分,那么当你读入cookie时,解析出值并设置新的过期以匹配。

不包含任何其他数据的示例,因此cookie实际上没有用处 - 您必须使用您要存储的实际数据以某种方式对其进行序列化:

HttpCookie cookie = HttpContext.Current.Request.Cookies[constantCookie];
DateTime expires = DateTime.Now.AddYears(1);

if (cookie == null) {
    cookie = new HttpCookie(constantCookie);
} else {
    // cookie.Value would have to be deserialized if it had real data
    expires = DateTime.Parse(cookie.Value);  
}

cookie.Expires = expires;
// save the original expiration back to the cookie value; if you want to store
// more than just that piece of data, you would have to serialize this with the
// actual data to store
cookie.Value = expires.ToString();

HttpContext.Current.Response.Cookies.Set(cookie);
相关问题