Asp.net mvc 5 在视图中使用User.IsInRole()

Asp.net mvc 5 在视图中使用User.IsInRole(),asp.net-mvc-5,asp.net-identity-2,isinrole,Asp.net Mvc 5,Asp.net Identity 2,Isinrole,在我的mvc5项目中,为未经授权的用户禁用操作链接,我喜欢这样做 @if (User.IsInRole("Admin") | User.IsInRole("Manager")) { @Html.ActionLink("Add New Record", "ProductTypeIndex", "ProductType") } 但是如果有很多角色需要检查,那么这个@if()就会变长。如何避免这种情况?我是否需要自定义帮助程序(如果需要,我如何处理)?谢谢你的帮助 <%

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

@if (User.IsInRole("Admin") | User.IsInRole("Manager"))
{ 
        @Html.ActionLink("Add New Record", "ProductTypeIndex", "ProductType")
} 
但是如果有很多角色需要检查,那么这个@if()就会变长。如何避免这种情况?我是否需要自定义帮助程序(如果需要,我如何处理)?谢谢你的帮助


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

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

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
} 

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

虽然此代码片段可以解决问题,但确实有助于提高您文章的质量。请记住,您将在将来为读者回答这个问题,而这些人可能不知道您的代码建议的原因。这是迄今为止最好、最简单的答案,并且完全是不言自明的。非常感谢您提供的解决方案:)抱歉,回复太晚。因为我有几天不能来stackoverflow。我稍微修改了一下,以便能够使用与authorize属性中相同的字符串:
authorize(Roles=“group1,group2,group3”)
。你可以找到我的版本。这样,您也可以使用:
User.isInyRoles(“组1、组2、组3”)