2012-11-03 73 views

回答

2
[Serializable] 
     public class CookieDto 
     { 
      public string Username { get; set; } 
      public string UserId { get; set; } 
      public string AuthenticationKey { get; set; } 
      public bool Persist { get; set; } 
      public string RememberMeToken { get; set; } 
     } 

堅持方法,

public void Persist(CookieDto cookieDto, bool persistent) 
{ 
    var serializer = new XmlSerializer(); 
    var serializedCookie = serializer.Serialize(cookieDto); 
    var ticket = new FormsAuthenticationTicket(1, cookieDto.Username, DateTime.Now, DateTime.Now.AddDays(90), 
     persistent, serializedCookie); 
    var encryptedTicket = FormsAuthentication.Encrypt(ticket); 

    var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket) { Expires = DateTime.Now.AddDays(90) }; 
    HttpContext.Current.Response.Cookies.Add(cookie); 
} 

獲取方法,

public CookieDto GetCookie() 
     { 
      var cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName]; 
      if (cookie != null && !string.IsNullOrEmpty(cookie.Value)) 
      { 
       var ticket = FormsAuthentication.Decrypt(cookie.Value); 
       var serializer = new XmlSerializer(); 

       return serializer.Deserialize<CookieDto>(ticket.UserData); 
      } 

      return null; 
     } 

remove方法,

public void RemoveCookie() 
{ 
    FormsAuthentication.SignOut(); 
} 

祝你好運!

+1

謝謝,不錯的片段。 –