这里我的cookie创建代码: 这是控制器(model.RememberMe是一个复选框值)
int timeout = (model.RememberMe) ? (int) FormsAuthentication.Timeout.TotalMinutes : Session.Timeout;//4h
HttpCookie cookie = accountService.GetCookie(userId, model.RememberMe, timeout);
Response.Cookies.Add(cookie);
Logger.Debug("POST: AccountController LogOn end.");
result = returnUrl != null
? RedirectToLocal(returnUrl)
: RedirectToAction("Index", "Profile", new {id = userId});
创建cookie的服务方法
public HttpCookie GetCookie(int userId, bool rememberMe, int timeout)
{
Logger.Trace("AccountService GetCookie start with arguments:" +
" userId = {0}, rememberMe = {1}.", userId, rememberMe);
var authTicket = new FormsAuthenticationTicket(
1,
Convert.ToString(userId),
DateTime.Now,
DateTime.Now.AddMinutes(timeout),
rememberMe,
string.Empty,
"/"
);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName,
FormsAuthentication.Encrypt(authTicket));
Logger.Debug("Cookie for user with userId = {0} has created", userId);
Logger.Trace("AccountService GetCookie end.");
return cookie;
}
但遗憾的是,RememberMe不工作,cookies在浏览器会话结束时到期。为什么?
What is the purpose of FormsAuthenticationTicket isPersistent property?这里有一些答案,但我不明白为什么它不起作用?
答案 0 :(得分:0)
您的代码与您链接的SO答案之间的区别在于:
FormsAuthentication.SetAuthCookie(model.UserName, true);
这使得Cookie具有基于IsPersistent
属性的正确到期时间。但是,如果您使用构造函数返回cookie,就像在代码中一样:
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName,
FormsAuthentication.Encrypt(authTicket));
然后将到期时间设置为browser-session,因为这是HttpCookie
类的默认行为:what is the default expiration time of a cookie
所以你可能有两种选择。使用您链接的答案中列出的FormsAuthentication.SetAuthCookie
方法,或添加:
cookie.Expires = DateTime.Now.AddMinutes(10); // or whatever you want