加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-16 03:53:44 所属栏目:asp.Net 来源:网络整理
导读:是否可以更新ASP.NET cookie值而无需更新到期时间?我发现,如果我尝试更新Cookie而不更新过期,则该cookie不再存在.我有以下代码,我试图修改.如果每次更新cookie值,到期时到期有什么意义? HttpCookie cookie = HttpContext.Current.Request.Cookies[constant
是否可以更新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);

解决方法

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);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读