C# 如何检查用户是否属于具有 MVC4 简单成员资格的几种不同角色中的任何一种?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14477757/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:56:43  来源:igfitidea点击:

How can I check if a user is in any one of a few different roles with MVC4 Simple membership?

c#.netasp.net-mvcasp.net-mvc-3asp.net-mvc-4

提问by

I understand that a good way to check if an user is in a role is:

我知道检查用户是否处于角色的一种好方法是:

if (User.IsInRole("Admin"))
{

}

However How can I check if my user is in one of the "Author", "Admin" or "Super" roles? Is there a way to do this without coding "User.IsInRole" for each of the roles?

但是,如何检查我的用户是否属于“作者”、“管理员”或“超级”角色之一?有没有办法在不为每个角色编码“User.IsInRole”的情况下做到这一点?

采纳答案by mattytommo

EDIT: Without coding each role, do it a LINQ extension method, like so:

编辑:不编码每个角色,做一个 LINQ 扩展方法,像这样:

private static bool IsInAnyRole(this IPrincipal user, List<string> roles)
{
    var userRoles = Roles.GetRolesForUser(user.Identity.Name);

    return userRoles.Any(u => roles.Contains(u));
}

For usage, do:

对于使用,请执行以下操作:

var roles = new List<string> { "Admin", "Author", "Super" };

if (user.IsInAnyRole(roles))
{
    //do something
}

Or without the extension method:

或者没有扩展方法:

var roles = new List<string> { "Admin", "Author", "Super" };
var userRoles = Roles.GetRolesForUser(User.Identity.Name);

if (userRoles.Any(u => roles.Contains(u))
{
    //do something
}

回答by Paul Turner

There's no built-in way to check if a user is in multiple roles, but it's pretty trivial to create a nice extension method to handle it for you:

没有内置的方法来检查用户是否具有多个角色,但是创建一个很好的扩展方法来为您处理它是非常简单的:

public static bool IsInAnyRole(this IPrincipal principal, params string[] roles)
{
    return roles.Any(principal.IsInRole);
}

Usage then is:

用法是:

if (User.IsInAnyRole("Admin", "Author", "SuperUser"))
{

}

回答by Venkata Tata

You can also use

你也可以使用

if(Roles.GetRolesForUser(model.UserName).Contains("Admin")){
}

回答by Cyberdrew

I wanted to elaborate a little on mattytommo's answer, here is what I use:

我想详细说明 mattytommo 的答案,这是我使用的:

Extension Method:

扩展方法:

public static bool IsInAnyRole(this IPrincipal user, string[] roles)
        {
            //Check if authenticated first (optional)
            if (!user.Identity.IsAuthenticated) return false;
            var userRoles = Roles.GetRolesForUser(user.Identity.Name);
            return userRoles.Any(roles.Contains);
        }

Constants:

常数:

public static class Role
{
    public const string Administrator = "Administrator";
    public const string Moderator = "Moderator";
}

Usage:

用法:

if (User.IsInAnyRole(new [] {Role.Administrator,Role.Moderator}))
{
    //Do stuff
}

回答by user007

I used the below code. In my case, I had a semi colon de-limited string as the parameter which is read from web.config. You may change the below code easily if you are passing a List.

我使用了下面的代码。就我而言,我有一个以分号分隔的字符串作为从 web.config 读取的参数。如果您正在传递一个列表,您可以轻松更改以下代码。

public class ActiveDirectoryGroup
{
    public static bool IsInAnyRole(string adRoles)
    {
        return adRoles.Split(Convert.ToChar(";")).Any(role => !string.IsNullOrEmpty(role.Trim()) && HttpContext.Current.User.IsInRole(role.Trim()));
        //If list is passed use below
        //return listParameter.Any(role => !string.IsNullOrEmpty(role.Trim()) && HttpContext.Current.User.IsInRole(role.Trim()));
    }
}

In web.config:

在 web.config 中:

<appSettings>
  <add key="ADGroup" value="Domain\Admin;Domain\Supervisor;Domain\Manager;" />
</appSettings>

I used it like below in my page load:

我在页面加载中使用它如下:

if (ActiveDirectoryGroup.IsInAnyRole(ConfigurationManager.AppSettings["ADGroup"]))
{
  //do something
}

回答by Francesco Ceresa

Please, use this simple way :

请使用这个简单的方法:

@using Microsoft.AspNet.Identity

@if (Request.IsAuthenticated)
{
    if (User.IsInRole("Administrator") || User.IsInRole("Moderator"))
    {
        ... Your code here
    }
}

回答by César León

In my case i just have one role per user. So i did it like this:

就我而言,我每个用户只有一个角色。所以我是这样做的:

if (User.Roles.FirstOrDefault().RoleId == "7b433246-5881-4ace-bbaa-e5514191171c") {
    //Do something
}

回答by Tuncay Ermi?

What about this?

那这个呢?

 if (User.Roles.Count() != 0)
     {
       //User is not in any role
     }else
     {
       //User is in at least one role
     }