c# - 如果 User.IsInRole 带有字符串数组?

标签 c# asp.net-mvc forms-authentication

我正在尝试构建自定义验证,以检查角色是否包含用户。我在使用字符串数组时遇到问题,检查它是否包含特定值的最佳方法是什么?

    public string[] AuthRoles { get; set; }


    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {

        if (AuthRoles.Length > 0)
        {

            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {

               RedirectToRoute(filterContext,
               new
               {
                   controller = "AdminLogin",
                   action = "AdminLogin"
               });

            }
            else
            {
                bool isAuthorized = filterContext.HttpContext.User.IsInRole(this.AuthRoles.??);

                if (!isAuthorized)
                    throw new UnauthorizedAccessException("You are not authorized to view this page");
            }
        }
        else
        {
            throw new InvalidOperationException("No Role Specified");
        }

我应该如何修改 User.IsInRole 的检查以便它处理数组?

最佳答案

怎么样:

bool isAuthorized = 
    this.AuthRoles.Any(r => filterContext.HttpContext.User.IsInRole(r));

编辑:(假设成为任何角色的成员就足以获得授权。)

关于c# - 如果 User.IsInRole 带有字符串数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2175669/

相关文章:

asp.net - 如何防止 Formsauthentication 阻止 css 和图像?

c# - 从 C# 调用 web 服务并发送未转义的 xml

c# - 改变可写位图的大小

c# - 将列表对象绑定(bind)到 javascript 数组

google-chrome-extension - 使用现有站点身份验证的 Chrome 扩展程序身份验证

asp.net - ASPXAUTH cookie 没有被保存

C# - 计算缩进级别 XML

c# - 何时复制 C# 值/对象,何时复制其引用?

javascript - ApiController返回Json结果无法解析,为什么数据类型:"json"不起作用?

javascript - AJAX 发布成功后如何调用 Kendo Treeview (服务器数据绑定(bind)类型)?