编程语言
首页 > 编程语言> > c# – 如何检查是否只有一个角色匹配?

c# – 如何检查是否只有一个角色匹配?

作者:互联网

我需要按角色过滤用户,但所有用户都属于两个角色

示例:一个用户的Admin和Group1,另一个用户的User和Group1.

现在我想通过Group1 Role过滤它们并忽略Admin和User.

public ViewResult Index()
{
    string[] roles = Roles.GetRolesForUser();
    var group = string.Join(" ", roles ); 
    group = group.Replace("Admin", "");//Used this to single out Group1 from Admin user
    return View(new UserViewModel
                    {
                        Users = _userService.FindAll().Where(x => Roles.GetRolesForUser(x.UserName).Contains(group)),
                        Roles = roles
                    });
}

这不会出错,但会显示为空.我想我知道为什么但仍然无法弄清楚如何解决它…

解决方法:

public ViewResult Index()
{
   var roleFilter = Roles.GetRolesForUser().First(r => !r.equals("Admin"));

   return View(new UserViewModel
                {
                    Users = _userService.FindAll().Where(x => Roles.GetRolesForUser(x.UserName).Contains(roleFilter)),
                    Roles = new [] {roleFilter}
                });
}

标签:c,asp-net-mvc,membership
来源: https://codeday.me/bug/20190625/1288201.html