Jak mogę sprawdzić, czy użytkownik jest w jednej z kilku różnych ról z członkostwem MVC4 Simple?

Rozumiem, że dobrym sposobem na sprawdzenie, czy użytkownik jest w roli jest:

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

}

Jak jednak mogę sprawdzić, czy mój użytkownik jest w jednej z ról" Autor"," Administrator "lub" Super"? Czy istnieje sposób, aby to zrobić bez kodowania " User.IsInRole " dla każdej z ról ?

Author: mattytommo, 2013-01-23

7 answers

EDIT: bez kodowania każdej roli, zrób to metodą rozszerzenia LINQ, jak tak:

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

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

Do użycia, do:

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

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

Lub bez metody rozszerzenia:

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

if (userRoles.Any(u => roles.Contains(u))
{
    //do something
}
 43
Author: mattytommo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-11-12 09:50:12

Nie ma wbudowanego sposobu, aby sprawdzić, czy użytkownik jest w wielu rolach, ale to dość trywialne, aby stworzyć ładną metodę rozszerzenia, aby obsłużyć go za Ciebie:

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

Użycie to:

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

}
 43
Author: Paul Turner,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-10 15:12:21

Chciałem trochę rozwinąć odpowiedź mattytommo, oto czego używam:

Metoda Rozszerzenia:

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);
        }

Stałe:

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

Użycie:

if (User.IsInAnyRole(new [] {Role.Administrator,Role.Moderator}))
{
    //Do stuff
}
 1
Author: Cyberdrew,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-31 16:48:30

Możesz również użyć

if(Roles.GetRolesForUser(model.UserName).Contains("Admin")){
}
 0
Author: Venkata Tata,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-01-23 13:57:38

Użyłem poniższego kodu. W moim przypadku miałem semi colon de-limited string jako parametr, który jest odczytywany z sieci.config. Możesz łatwo zmienić poniższy kod, jeśli przekazujesz 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()));
    }
}

W sieci.config:

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

Użyłem go jak poniżej w ładowaniu strony:

if (ActiveDirectoryGroup.IsInAnyRole(ConfigurationManager.AppSettings["ADGroup"]))
{
  //do something
}
 0
Author: user007,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-27 18:21:17

W moim przypadku mam tylko jedną rolę na użytkownika. Więc zrobiłem to tak:

if (User.Roles.FirstOrDefault().RoleId == "7b433246-5881-4ace-bbaa-e5514191171c") {
    //Do something
}
 0
Author: César León,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-09 15:00:32

Proszę, użyj tego prostego sposobu:

@using Microsoft.AspNet.Identity

@if (Request.IsAuthenticated)
{
    if (User.IsInRole("Administrator") || User.IsInRole("Moderator"))
    {
        ... Your code here
    }
}
 -1
Author: Francesco Ceresa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-19 15:14:53