Search code examples
c#.netasp.net-mvcasp.net-identity

Simplify User.IsInRole() check asp.net mvc


In our asp.net mvc project in .cshtml views often you can find:

if (User.IsInRole("Admin") || User.IsInRole("Supervisor"))

I'd like to simplify current syntax like this: if (IsAdminOrSupervisor(User))

So, I need to make a html-helper, or some backend helper. Could you help me how can I do this? Thank you!


Solution

  • Create an extension to your identity for checking multiple roles:

    public static bool IsAdminOrSupervisor(this IPrincipal user, List<string> roles)
    {
        var userRoles = Roles.GetRolesForUser(user.Identity.Name);
    
        return userRoles.Any(u => roles.Contains(u));
    }
    

    Then you can use this like:

    var roles = new List<string> { "Admin", "Supervisor" };
    
    if (User.IsAdminOrSupervisor(roles))
    {
       //Action
    }
    

    Tips: You need to reference the class that holds this method to your Razor:

    @Using NameSpace.ClassName