2011-02-03 68 views
8

這是我的功能,當登錄成功時會調用它。 (我是很新的這FormAuthentication東西)FormsAuthenticationTicket過期過期

public static void CreateLoginCookie(User u) 
{ 
    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(u.Id.ToString(), true, 9*60); 
    string encryptedTicket = FormsAuthentication.Encrypt(ticket); 
    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket) { Expires = DateTime.Now.AddHours(9) }; 
    HttpContext.Current.Response.Cookies.Add(cookie); 
} 

在web.config我有

<authentication mode="Forms"> 
    <forms loginUrl="~/Default/Login" timeout="540" /> 
</authentication> 

我希望用戶保持登錄狀態,9小時,但它不工作。他們在一兩個小時後退出。

有人能告訴我我失蹤了什麼嗎?

+2

你確定它的票,而不是即將到期的會議? – 2011-04-19 03:49:06

回答

1

你看過修改web.config文件中的超時了嗎?

<forms 
    name="name" 
    loginUrl="URL" 
    defaultUrl="URL" 
    protection="[All|None|Encryption|Validation]" 
    timeout="[MM]" 
    path="path" 
    requireSSL="[true|false]" 
    slidingExpiration="[true|false]"> 
    enableCrossAppRedirects="[true|false]" 
    cookieless="[UseUri|UseCookies|AutoDetect|UseDeviceProfile]" 
    domain="domain name" 
    ticketCompatibilityMode="[Framework20|Framework40]"> 
    <credentials>...</credentials> 
</forms> 
+0

是的,謝謝,我有540超時但它沒有工作。我更新了這個問題。 – Aximili 2011-02-03 01:49:57

1

我用這個片段,併爲我的作品,看看這個:

 FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket( 
               1,          // Ticket version 
               username,         // Username associated with ticket 
               DateTime.Now,        // Date/time issued 
               DateTime.Now.AddDays(1),     // Date/time to expire 
               isPersistent,        // "true" for a persistent user cookie 
               dataStore,        // User-data, in this case the roles 
               FormsAuthentication.FormsCookiePath);  // Path cookie valid for 

     // Encrypt the cookie using the machine key for secure transport 
     string Hash = FormsAuthentication.Encrypt(Ticket); 
     HttpCookie Cookie = new HttpCookie(FormsAuthentication.FormsCookieName, Hash); 

     // Set the cookie's expiration time to the tickets expiration time 
     if (Ticket.IsPersistent) 
      Cookie.Expires = Ticket.Expiration; 
3

這可能是因爲應用程序池回收的發生。

認證cookie使用機器密鑰加密。 似乎默認情況下這些機器密鑰是在每個應用程序池重新啓動時生成的。 然後,您的應用程序閒置一段時間(在應用程序池設置中配置),您的應用程序池將被回收。

所以你需要生成靜態機器密鑰。

這個問題是有關您: Can a FormsAuthenticationTicket survive an app pool recycle?