Roles.GetRolesForUser() 在布局视图中不返回角色

Roles.GetRolesForUser() in Layout view not returning roles

@Roles.GetRolesForUser() 在 Razor 布局视图中没有返回角色。 @Roles.GetRolesForUser().Count() 为 0。

@Roles.IsUserInRole('name_of_logged_in_role') returns true 在同一地点的同一视图中。

剃刀视图:

<p>
    @User.Identity.Name //Output: MyName
    @Roles.GetRolesForUser().Count()  //Output: 0
    @Roles.IsUserInRole("Radiologist")  //Output: True
</p>

更新

@Roles.GetRolesForUser(User.Identity.Name).Length //Output: 0
@Roles.GetRolesForUser(User.Identity.GetUserName()).Length //Output: 0

经过广泛的研究,我终于找到了问题所在。我能够在 Web 应用程序中重现该问题。显然,您不能像使用 GetRolesForUser 方法那样将 ASP.NET IdentitySimple Membership 结合使用。 Roles 对象默认设置为 Simple Membership 使用默认提供者,但您似乎使用 ASP.NET Identity 而不是 简单会员资格 。我什至没有注意到差异,直到我想知道为什么它不起作用。

你得到 string[0] 的原因是因为 GetRolesForUser 对你的数据库中不存在的 table 执行了 sql 查询。
IsUserInRole 工作的原因或多或少是它甚至没有使用默认提供程序来检查它是否使用了 CacheRolesInCookie

If CacheRolesInCookie is true, then roleName may be checked against the roles cache rather than the specified role provider.

因此,从技术上讲,它转到了默认提供程序和 return string[0] 列出的 connectionString,因为数据库中没有包含该 connectionString 的数据。将您当前的数据库添加到提供程序也无济于事,因为 Simple Membership 数据库架构不同于 ASP.NET Identity

也就是说,您应该像这样通过用户名获取角色:

简单的解决方案:

public List<string> GetRoles(string UserName)
{    List<string> roles = new List<string>();
    if (!string.IsNullOrWhiteSpace(UserName))
    {
        ApplicationUser user = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
        var account = new AccountController();

        roles = account.UserManager.GetRoles(user.Id);         
    }            
    return roles;
}

已更新

扩展解决方案:

您可以在您的上下文中扩展 ASP.NET 身份 角色

http://www.codeproject.com/Articles/799571/ASP-NET-MVC-Extending-ASP-NET-Identity-Roles