FormsAuthenticationTicket过期过期

这是我在登录成功时调用的函数。 (我对这个FormAuthentication的事情很新)

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我有

    

我希望用户保持登录状态9小时,但它不起作用。 他们会在一两个小时后退出。

有人能告诉我我错过了什么吗?

可能由于应用程序池回收而发生。

身份validationcookie使用机器密钥加密。 似乎默认情况下,这些机器密钥是在每个应用程序池重新启动时生成的。 然后,您的应用程序空闲一段时间(在应用程序池设置中配置)您的应用程序池将被回收。

所以你需要生成静态机器密钥。

这个问题与您的问题有关: FormsAuthenticationTicket可以在应用程序池回收中存活吗?

您是否考虑过修改web.config文件中的超时?

  enableCrossAppRedirects="[true|false]" cookieless="[UseUri|UseCookies|AutoDetect|UseDeviceProfile]" domain="domain name" ticketCompatibilityMode="[Framework20|Framework40]"> ...  

我已经使用了这个片段,它对我有用,看看这个:

  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;