如果 User.IsInRole 带有字符串数组?
我正在尝试构建自定义验证,在其中检查角色是否包含用户。我在使用字符串数组时遇到问题,检查它是否包含特定值的最佳方法是什么?
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 的检查以便它处理数组?
Im trying to build a custom validation where I check if the role contains a user. And I'm having problems with string array, what is best way to check if it contains a specific value?
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");
}
How should I modify the check for User.IsInRole so it handles the array?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
怎么样:
编辑:(假设成为任何角色的成员就足以获得授权。)
How about:
Edit: (Assuming that being member of any of the roles is enough to be authorized.)
如果您希望用户同时拥有
AuthRoles
中的所有角色,您应该:如果仅成为至少一个所需角色的成员就足够了,请使用
Any< /代码>:
If you want the user to have all the roles in the
AuthRoles
at the same time, you should:If just being a member of at least one of the required roles is enough, use
Any
:您可以使用简单的 linq 表达式来完成此操作:
You can do it with a simple linq expression:
您需要检查每个字符串
You need to check each string