2012-05-31 98 views
1

我遇到的問題是Cookie不會在瀏覽器會話中持續存在。如果我關閉並重新打開瀏覽器,則下一個請求中的Cookie不會傳遞到服務器。Asp.Net FormsAuth Cookie不會持續

這是我如何創建當用戶登錄cookie的:

var ticket = new FormsAuthenticationTicket(
    1 /*version*/, 
    user.Id, 
    now, 
    now.Add(ExpirationTimeSpan), /* ExpirationTimeSpan = TimeSpan.FromHours(6) */ 
    true /*createPersistentCookie*/, 
    userData, 
    FormsAuthentication.FormsCookiePath); 

var encryptedTicket = FormsAuthentication.Encrypt(ticket); 

var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket) 
        { 
         HttpOnly = true, 
         Secure = FormsAuthentication.RequireSSL, 
         Path = FormsAuthentication.FormsCookiePath 
        }; 
if (FormsAuthentication.CookieDomain != null) 
{ 
    cookie.Domain = FormsAuthentication.CookieDomain; 
} 

var httpContext = this.contextAccessor.Current(); 
httpContext.Response.Cookies.Add(cookie); 

我在做什麼錯?

回答

0

我認爲你需要設置像這樣的HttpCookie到期....

var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket) 
     { 
      HttpOnly = true, 
      Secure = FormsAuthentication.RequireSSL, 
      Path = FormsAuthentication.FormsCookiePath, 
      Expires= = DateTime.UtcNow.AddHours(6); 
     };