15

在我的 mvc5 项目中,为未经授权的用户禁用操作链接,我确实喜欢这样

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

但是如果有很多角色需要检查,那么这个@if() 就会变得很长。如何避免这种情况?我是否需要为此自定义助手(如果需要,我该如何处理)?帮助表示赞赏..

4

2 回答 2

36

您可以编写自己的扩展方法并在代码中使用它。

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));
    }
}

现在你可以简单地调用这个扩展方法:

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

虽然您也可以在视图中使用这些扩展方法,但尽量避免在视图中编写应用程序逻辑,因为视图不容易进行单元测试。

于 2015-09-03T20:42:27.513 回答
-3
<% if (Page.User.IsInRole("Admin")){ %>
于 2015-09-03T18:48:59.660 回答