我正在尝试使用ASP.NET 4.0中的“记住我”功能实现一个登录表单。
我已将web.config中的超时选项设置为1年(525600),但在我登录后的一段随机时间后,我总是被注销。
cookie是正确创建的,我可以在浏览器中看到它具有正确的过期值(2014年9月),但似乎这段cookie在一段时间之后不再被ASP.NET环境所取代。
我尝试使用以下方式登录:
FormsAuthentication.RedirectFromLoginPage(username, true);
或:
FormsAuthentication.SetAuthCookie(username, true);
Response.Redirect("/");
或使用此自定义代码:
DateTime expiryDate = DateTime.Now.AddMinutes(FormsAuthentication.Timeout.TotalMinutes);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(2, userid, DateTime.Now, expiryDate, true, String.Empty);
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie authenticationCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
authenticationCookie.Expires = ticket.Expiration;
Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
Response.Cookies.Add(authenticationCookie);
Response.Redirect(FormsAuthentication.GetRedirectUrl(username, false));
但结果总是一样的。 cookie存在,但过了一段时间后它就不再使用了。
Web.config就像这样:
<authentication mode="Forms">
<forms loginUrl="/login" defaultUrl="/" name="appName" path="/" timeout="525600" slidingExpiration="true"/>
</authentication>
奇怪的是,在我的本地测试环境(ASP.NET开发服务器)中,事情正常。只有在生产环境中它才能正常工作!
答案 0 :(得分:0)
@Felipe Garcia:我不知道我是否正在使用负载均衡器,我在公共服务器上。但是我试着像你说的那样配置MachineKey(使用生成器here),现在它似乎正常工作了!
谢谢!