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 に答える