2009-09-29 67 views

回答

3

您使用的是由ASP.NET提供的Authenication服務嗎?如果是這樣,它很容易。

+0

我在之前的項目上使用了FormsAuthentication方法,但想知道是否有其他方法來實現它。 – lnetanel

+0

當然有,通過手動分配一個cookie。 –

0

對我來說,解決方案是區分瀏覽器會話cookie(不要與asp.net會話cookie混淆)和持久cookie - 設置過期時間會創建一個持久cookie,這意味着它在瀏覽器時會被記住在到期時間內關閉並重新打開。以下作品適用於我:

public void SetAuthenticationCookie(LoginView loginModel) 
    { 
     if (!loginModel.RememberMe) 
     { 
     FormsAuthentication.SetAuthCookie(loginModel.Email, false); 
     return; 
     } 
     const int timeout = 2880; // Timeout is in minutes, 525600 = 365 days; 1 day = 1440. 
     var ticket = new FormsAuthenticationTicket(loginModel.Email, loginModel.RememberMe, timeout); 
     //ticket. 
     string encrypted = FormsAuthentication.Encrypt(ticket); 
     var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted) 
     { 
      Expires = System.DateTime.Now.AddMinutes(timeout), 
      HttpOnly = true 
     }; 
     HttpContext.Current.Response.Cookies.Add(cookie); 
    }