15

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

@if (User.IsInRole("Admin") | User.IsInRole("Manager"))
{ 
        @Html.ActionLink("Add New Record", "ProductTypeIndex", "ProductType")
} 

But if there are many roles to check then this @if() gets long. How to avoid this? Do i need custom helpers for this(if so how can i approach it)? Help appreciated..

Isuru
  • 950
  • 1
  • 13
  • 34

2 Answers2

36

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.

Sam FarajpourGhamari
  • 14,601
  • 4
  • 52
  • 56
  • Thank you very much for the solution :) Sorry for the late reply. Because i couldn't come to stackoverflow for few days. – Isuru Sep 07 '15 at 04:01
  • 2
    I changed it slightly to be able to use to use the same string as in the authorize attribute: `Authorize (Roles = "group1,group2,group3")`. You can find my version [here](https://gist.github.com/depuits/8ae37a2db0a44abea6bfc30c72349f27). This way you can also use: `User.IsInAnyRoles ("group1,group2,group3")` – ColmanJ Apr 12 '17 at 07:25
-3
<% if (Page.User.IsInRole("Admin")){ %>
  • 3
    While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Lynn Crumbling Sep 03 '15 at 21:42
  • This is by far the best and simplest answer, and is fully self-explanatory. – Pat James May 08 '16 at 20:30