User.IsInRole() 在视图中的使用 [英] Usage of User.IsInRole() in a View

查看:30
本文介绍了User.IsInRole() 在视图中的使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

推荐答案

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

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.

这篇关于User.IsInRole() 在视图中的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆