Usage of User.IsInRole() in a View

后端 未结 2 902
鱼传尺愫
鱼传尺愫 2020-12-03 08:37

In my mvc5 project to disable an action link for unauthorized users i did like this

@if (User.IsInRole(\"Admin\") | User.IsInRole(\"Manager\"))
{ 
        @H         


        
相关标签:
2条回答
  • 2020-12-03 08:48

    You could write your own extension method and use it in your code.

    public static class PrincipalExtensions
    {
        public static bool IsInAllRoles(this IPrincipal principal, params string[] roles)
        {
            return roles.All(r => principal.IsInRole(r));
        }
    
        public static bool IsInAnyRoles(this IPrincipal principal, params string[] roles)
        {
            return roles.Any(r => principal.IsInRole(r));
        }
    }
    

    Now simply you could call this extension method like this:

    // user must be assign to all of the roles  
    if(User.IsInAllRoles("Admin","Manager","YetOtherRole"))
    {
        // do something
    } 
    
    // one of the roles sufficient
    if(User.IsInAnyRoles("Admin","Manager","YetOtherRole"))
    {
        // do something
    } 
    

    While you could use these extension methods in views as well but try to avoid writing your apps logic in views as much as possible since views not unit testable easily.

    0 讨论(0)
  • 2020-12-03 09:03
    <% if (Page.User.IsInRole("Admin")){ %>
    
    0 讨论(0)
提交回复
热议问题