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

查看:1558
本文介绍了在视图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()获取长。如何避免这种情况?我是否需要为这种定制的助手(如果是的话我怎么能接近它)?帮助AP preciated ..

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

推荐答案

您可以编写自己的扩展方法,并在你的code使用它。

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天全站免登陆