Using User.IsInRole () in a View

In my mvc5 project, to disable the action link for unauthorized users, I liked this

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

But if there are many roles, then this @if () becomes long. How to avoid this? I need special assistants for this (if so, how can I approach it)? Help evaluate.

+7
asp.net-mvc-5 asp.net-identity-2 isinrole
source share
2 answers

You can 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 you can simply call this extension method as follows:

 // 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 } 

Although you could use these extension methods in your views, try to avoid writing application logic in the view as much as possible, since views cannot be easily tested.

+23
source share
 <% if (Page.User.IsInRole("Admin")){ %> 
-2
source share

All Articles