我创建了一个cookie并且它具有正确的到期日设置,但是当我去更新cookie并使用调试器检查它时,到期时间已经消失。发生了什么事?
' Cookie Helper: Updates cookie with the selected source ids
Protected Sub UpdateCookieFor(ByVal cookieName As String, ByVal sourceIds As String)
' Update cookie if it exists
If Request.Cookies(cookieName) IsNot Nothing Then
Response.Cookies(cookieName).Value = sourceIds
End If
End Sub
' Cookie Helper: Create cookie
Protected Sub CreateCookie(ByVal cookieName As String, ByVal sourceIds As String)
' Create cookie if it does not exist
If Request.Cookies(cookieName) Is Nothing Then
Response.Cookies(cookieName).Value = sourceIds
Response.Cookies(cookieName).Expires = DateTime.Now.AddYears(10)
End If
End Sub
答案 0 :(得分:0)
我今天刚遇到这个问题(使用C#)。显然,到期时间从未从浏览器发送到服务器,因此您始终必须设置该值。我在MSDN上阅读了这篇文章:
http://msdn.microsoft.com/en-us/library/aa289495(v=vs.71).aspx#vbtchaspnetcookies101anchor8
请参阅“过期是什么?”部分。
我能够通过在cookie中设置原始到期日期的值来解决这个问题,因此它将被发送到服务器。
HttpCookie myCookie = new HttpCookie(Constants.CookieName);
myCookie.Expires = DateTime.Now.AddDays(numberOfdaysToExpireCookie);
myCookie["MyKey"] = myValue;
myCookie["MyExpiry"] = myCookie.Expires.Ticks.ToString();
HttpContext.Current.Response.Cookies.Add(myCookie);
然后,在更新cookie时,我会阅读原始到期日并再次写出来。
//Get the expiry date that was stored
string cookieExpiryDateValue = myCookie.Values["MyExpiry"];
long ticks;
DateTime expiryDate = DateTime.Now.AddDays(numberOfdaysToExpireCookie);
if(long.TryParse(cookieExpiryDateValue, out ticks)){
expiryDate = new DateTime(ticks);
}
//Update the value in the cookie. Persist the expiry and domain
HttpCookie responseCookie = HttpContext.Current.Response.Cookies[Constants.CookieName];
responseCookie.Values["MyKey"] = cookieValues;
responseCookie.Values["MyExpiry"] = cookieExpiryDateValue;
responseCookie.Expires = expiryDate;