I create a cookie and it has the proper expiry set, but when I go to update the cookie and check it with the debugger the expiry is gone. What is going on?
' 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(cookieN开发者_运维问答ame).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
I just ran into this issue today (using C#). Apparently, the expiry is never sent to the server from the browser, so you always have to set the value. I read about this on MSDN at:
http://msdn.microsoft.com/en-us/library/aa289495(v=vs.71).aspx#vbtchaspnetcookies101anchor8
See the section: "What's the Expiration?"
I was able to work around this by setting a value in the cookie with the original expiry date, so it would be sent to the server.
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);
Then, when updating the cookie, I read in the original expiry and write it out again.
//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;
精彩评论