Usage of User.IsInRole() in a View

时光怂恿深爱的人放手 提交于 2019-11-26 16:37:16

问题


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..


回答1:


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.




回答2:


<% if (Page.User.IsInRole("Admin")){ %>


来源:https://stackoverflow.com/questions/32369229/usage-of-user-isinrole-in-a-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!