如果设置了 FormsAuthentication Ticket,为什么 User.IsInRole(“Admin”) 不起作用?

If FormsAuthentication Ticket is set, why doesn't User.IsInRole(“Admin”) work?

在调试器中,如果我深入 User 对象,我可以看到当前成员的 UserData 属性、((System.Web.Security.FormsIdentity(User.Identity)).Ticket.UserData,里面有 "admin"。

User.Identity.IsAuthenticated 有效,但 User.IsInRole("admin") return 错误。

如果 "admin" 在 UserData 属性 中,那么为什么 User.IsInRole("admin") return 不正确?

在我的登录方法中,我将验证票设置如下:

 FormsAuthenticationTicket _ticket = new FormsAuthenticationTicket(1, lUserName.Text, DateTime.Now, DateTime.Now.AddMonths(1), chk_remember.Checked, Role, FormsAuthentication.FormsCookiePath);
        string encTicket = FormsAuthentication.Encrypt(_ticket);
        HttpCookie _cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
        if (chk_remember.Checked)
            _cookie.Expires = DateTime.Now.AddMonths(1);
        Response.Cookies.Add(_cookie);

您需要将此代码放入您的 Global.asax

protected void Application_AuthenticateRequest(Object sender,
EventArgs e)
{
  if (HttpContext.Current.User != null)
  {
    if (HttpContext.Current.User.Identity.IsAuthenticated)
    {
     if (HttpContext.Current.User.Identity is FormsIdentity)
     {
        FormsIdentity id =
            (FormsIdentity)HttpContext.Current.User.Identity;
        FormsAuthenticationTicket ticket = id.Ticket;

        // Get the stored user-data, in this case, our roles
        string userData = ticket.UserData;
        string[] roles = userData.Split(',');
        HttpContext.Current.User = new GenericPrincipal(id, roles);
     }
    }
  }
}

更多信息你可以看这个linkform authentication