Asp.net

FormsAuthenticationTicket 的 UserData 屬性為空,儘管已設置

  • June 30, 2020

出於某種原因,我的身份驗證 cookie 的 UserData 屬性為空。這是程式碼:

var authCookie = FormsAuthentication.GetAuthCookie(userName, rememberUser.Checked);
// Get the FormsAuthenticationTicket out of the encrypted cookie
var ticket = FormsAuthentication.Decrypt(authCookie.Value);
// Create a new FormsAuthenticationTicket that includes our custom User Data
var newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, "userData");
// Update the authCookie's Value to use the encrypted version of newTicket
authCookie.Value = FormsAuthentication.Encrypt(newTicket);
// Manually add the authCookie to the Cookies collection
Response.Cookies.Add(authCookie);
FormsAuthentication.RedirectFromLoginPage(userName, rememberUser.Checked);

這是我嘗試訪問它的方法:

if (HttpContext.Current.Request.IsAuthenticated )
{
   var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
   if (authCookie != null)
   {
       var authTicket = FormsAuthentication.Decrypt(authCookie.Value);
       string data = authTicket.UserData;
       // data is empty !!!
   }
}

RedictFromLoginPage覆蓋您的 cookie。刪除此行並手動重定向 ( Response.Redirect)。

這是我幾天前回答的類似答案。

https://stackoverflow.com/a/16365000/296861

如果您自己創建FormsAuthenticationTicket ,則不能使用FormsAuthentication.SetAuthCookieFormsAuthentication.RedirectFromLoginPage

引用自:https://stackoverflow.com/questions/16594905