2014-11-21 28 views
0

这里我的cookie创建代码: 这是控制器(model.RememberMe是一个复选框值)来创建的cookie记得我(isPersistent)不要在窗体身份验证工作

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}); 

服务方法

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不工作,Cookie在浏览器会话结束时过期。为什么?

What is the purpose of FormsAuthenticationTicket isPersistent property?这里的某种答案,但我不明白为什么它不工作?

回答

0

你的代码之间的差异的SO回答您链接的是,他们使用:

FormsAuthentication.SetAuthCookie(model.UserName, true);

这使得基于该IsPersistent财产了适当的过期时间的cookie。但是,如果你在你的代码构造函数返回的cookie,如:

HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket));

那么到期时间将被设置为浏览器会话,因为这是HttpCookie类的默认行为:what is the default expiration time of a cookie

所以你可能有两个选择。使用您链接到的答案中概述的FormsAuthentication.SetAuthCookie方法,或者添加:

cookie.Expires = DateTime.Now.AddMinutes(10); // or whatever you want