2012-03-23 53 views
1

在我的登錄頁面中,我創建了FA cookie。如何在formAuthentication上傳輸鍵值對?

我想添加它到userId。

我然後重定向到我的默認頁面,

,我想讀的用戶ID。

我用這兩個輔助方法:

public static class NewWebHelpers 
{ 
    public static void CreateAuthCookie(string cookieName, string cookieValue) 
    { 
     //Get ASP.NET to create a forms authentication cookie (based on settings in web.config)~ 
     HttpCookie cookie = FormsAuthentication.GetAuthCookie(cookieName, false); 

     //Decrypt the cookie 
     FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value); 

     //Create a new ticket using the details from the generated cookie, but store the username & 
     //token passed in from the authentication method 
     FormsAuthenticationTicket newticket = new FormsAuthenticationTicket(
     ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, 
     ticket.IsPersistent, cookieValue); 

     // Encrypt the ticket & store in the cookie 
     cookie.Value = FormsAuthentication.Encrypt(newticket); 

     // Update the outgoing cookies collection. 
     System.Web.HttpContext.Current.Response.Cookies.Set(cookie); 
    } 


    public static string ReadAuthCookie(string cookieName) 
    { 
     //Get ASP.NET to create a forms authentication cookie (based on settings in web.config)~ 
     HttpCookie cookie = FormsAuthentication.GetAuthCookie(cookieName, false); 

     //Decrypt the cookie 
     FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value); 

     return ticket.UserData; 
    } 
} 

但得到String.Empty,而不是我進了用戶ID。

爲什麼?

回答

0

您正在創建一個新authcookieFormsAuthentication.GetAuthCookie而不是讀取與請求一起提供的一個。試試這個:

public static string ReadAuthCookie(string cookieName) 
{ 
    HttpCookie cookie = 
     HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName]; 
    FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value); 
    return ticket.UserData; 
}