2011-04-07 43 views
1

我創建了一個cookie並設置了正確的過期時間,但是當我去更新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

我今天剛剛遇到這個問題(使用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;