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

ahe*_*ick 6 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);
Run Code Online (Sandbox Code Playgroud)

Jon*_*ams 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);
Run Code Online (Sandbox Code Playgroud)

  • 很好的答案,虽然不只是ASP.NET没有初始化到期日 - 一般来说,cookie到期日是'只写'并且不会在http请求中公布给Web服务器. (2认同)