角色添加到 HttpContext.current.user 但 isInRole(rolename) 不工作

Role added to HttpContext.current.user but isInRole(rolename) is not working

这是我关于身份验证和授权的代码

public class SessionContext
{
    public void setAuthenticationToken(UserAccount userAccount,bool isPersistant,string name)
    {
        string data = new JavaScriptSerializer().Serialize(userAccount.Roles);
        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,name,DateTime.Now,DateTime.Now.AddYears(1),isPersistant,data);
        var encryptedCookieData = FormsAuthentication.Encrypt(ticket);
        HttpCookie httpCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedCookieData) { HttpOnly=true,Expires=ticket.Expiration };
        HttpContext.Current.Response.Cookies.Add(httpCookie);
    }
} 

我的Global.asax有这个方法:

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
    HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];

    if (authCookie != null)
    {
        FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
        
        string[] roles = authTicket.UserData.Split(new Char[] { ',' });
        
        GenericPrincipal userPrincipal = new GenericPrincipal(new GenericIdentity(authTicket.Name), roles);
        
        HttpContext.Current.User = userPrincipal;
        
        Debug.WriteLine(roles.FirstOrDefault() +" "+ userPrincipal.IsInRole("Admin"));
    }
}

但是当我使用 [Authorize(Roles="Admin")] 授权时不起作用。

我尝试了这些解决方案但没有奏效:

  1. 我使用了 [CustomAthorize(Roles="Admin")],在 Whosebug
  2. 中进行了解释
  3. 我用了Thread.CurrentPrincipal=userPrincipal

注意: 如您所见,我在 Global.asax 中添加了 Debug.WriteLine() 以向我显示 userPrincipal 角色状态,但始终 returns假的。

注意:如果可以,请告诉我另一种使用不基于 OWIN 的授权和身份验证的方法

我意识到问题是在将角色名称保存到 HttpContext 时,它在保存角色名称时使用了“”,而在保存时必须不使用“”