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