【问题标题】:MVC4 .Net 4.5 User Role IssueMVC4 .Net 4.5 用户角色问题
【发布时间】:2013-11-12 06:57:33
【问题描述】:

我正在将我的应用程序从 mvc4 asp.net4 更新到 .net4.5 并且用户角色不起作用。

目前我正在使用此代码

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);
            Context.User = userPrincipal;
 //Or
//HttpContext.Current.User = userPrincipal;
        }
    }

我可以在上面的帮助下为当前用户添加角色并检查控制器中的用户角色 [Authorize(Roles = "Admin, Guest")] 或 User.IsInRole("Admin")

但我的代码在 MVC4 ASP.Net 4.5 中不起作用

我不想使用角色提供者。例如Roles.CreateRole 或 Roles.AddUserToRole

有人可以帮我解决这个问题吗 谢谢

【问题讨论】:

    标签: c# asp.net asp.net-mvc asp.net-mvc-4


    【解决方案1】:

    即使在 MVC 4 .NET 4.0 下,我也可以重现该问题。不知道为什么它不能在 .NET 4.0 下为您重现。

    看起来即使您替换了 Application_AuthenticateRequest 中的主体。最终通过简单的会员代码将主体替换为 System.Web.Security.RolePrincipal ,并且我相信 RolePrincipal 会查询数据库以获取用户的角色数据。由于您不使用 RoleProvider,RolePrincipal 将不包含任何角色数据,它会删除之前委托人的角色数据。

    一种可能的解决方法是将 Application_AuthenticateRequest 更改为 Application_AuthorizeRequest,这发生在简单的成员资格设置 RolePrincipal 之后。 顺便说一句,您应该将 HttpContext.User 和 Thread.CurrentPrincipal 都设置为同一个用户。

    如果上述解决方法适合您,请告诉我。

    【讨论】:

    • 您好 Hongye,感谢您的帮助,它现在可以正常工作了,是的,您是正确的主要用户角色,已被 System.Web.Security.RolePrincipal 替换,并试图从数据库中获取角色。
    【解决方案2】:

    在 .NET 4.5 中,GenericPrincipal 现在继承自 System.Security.Claims.ClaimsPrincipal;以前它继承自 System.Object。

    我们的应用程序将其存储在会话中(在数据库中),但它似乎以不同的方式序列化和反序列化一些内部声明,因为我遇到了角色丢失的类似问题。

    【讨论】:

      猜你喜欢
      • 2013-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-18
      • 2012-08-13
      • 2016-10-03
      • 1970-01-01
      相关资源
      最近更新 更多