这是我的函数,在登录成功时调用。(我对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中,我有
<authentication mode="Forms">
<forms loginUrl="~/Default/Login" timeout="540" />
</authentication>我希望用户保持登录9小时,但它不起作用。他们在一两个小时后被注销。
有人能告诉我我错过了什么吗?
发布于 2012-05-18 13:00:51
由于应用程序池回收,可能会发生这种情况。
身份验证cookie使用机器密钥进行加密。似乎在默认情况下,这些机器密钥是在每次应用程序池重新启动时生成的。然后您的应用程序空闲一段时间(在应用程序池设置中配置),您的应用程序池将被回收。
所以你需要生成静态的机器密钥。
此问题与您的问题相关:Can a FormsAuthenticationTicket survive an app pool recycle?
发布于 2011-02-03 09:35:00
您是否考虑过修改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>发布于 2011-04-19 11:46:11
我已经使用了这个代码片段,它对我来说很有效,看看这个:
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;https://stackoverflow.com/questions/4881864
复制相似问题