简体   繁体   English

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

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

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”的情况下做到这一点?

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"))
{

}

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
}

You can also use你也可以使用

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

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
}

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.就我而言,我有一个以分号分隔的字符串作为从 web.config 读取的参数。 You may change the below code easily if you are passing a List.如果您要传递列表,则可以轻松更改以下代码。

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
}

Please, use this simple way :请使用这个简单的方法:

@using Microsoft.AspNet.Identity

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

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
}

What about this?那这个呢?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何访问 mvc4 中的成员资格表? - How can I have access in membership tables in mvc4? 我可以在不实现整个Membership provider爵士乐的情况下,向几个ASP.NET MVC路由添加简单身份验证的快速方法是什么? - What is a quick way I can add simple authentication to a few ASP.NET MVC routes, without implementing the whole Membership provider jazz? MVC5身份和MVC4简单会员有什么区别? - What is the difference between MVC5 identity and MVC4 simple membership? 如何在View MVC5中检查用户角色 - How to check user roles in View MVC5 MVC3 / MVC4中的简单成员资格和角色提供程序 - Simple Membership and Role Provider in MVC3/MVC4 检查用户是否在线mvc4 - Check if a user is online mvc4 MVC4简单成员资格何时会发生自动登录? - MVC4 Simple Membership When Does Automatic Login Occur? 使用实体框架poco基于不同用户角色的MVC4数据注释验证 - MVC4 data annotation validation based on different user roles using entity framework poco's Asp.net MVC-如何在不知道这些角色的情况下获得用户角色? - Asp.net MVC - How can I get user roles without knowing these roles? 在MVC4中,如何检查用户登录名和密码? - In MVC4, how do I do my own check on user login and password?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM