多角色授权属性 [英] Authorize Attribute with Multiple Roles
问题描述
我想向控制器添加授权,一次为多个角色.
I would like to add Authorization to a controller, for multiple Roles at once.
通常看起来像这样:
[Authorize(Roles = "RoleA,RoleB,RoleC")]
public async Task<ActionResult> Index()
{
}
但我已将我的角色存储在常量中,因为它们可能会在某些时候更改或扩展.
But I have stored my Roles in consts, since they might change or be extended at some point.
public const RoleA = "RoleA";
public const RoleB = "RoleB";
public const RoleC = "RoleC";
我不能这样做,因为必须在编译时知道字符串:
I cannot do this, since the string must be known at compile time:
[Authorize(Roles = string.join(",",RoleA,RoleB,RoleC)]
public async Task<ActionResult> Index()
{
}
有没有办法绕过这个问题?
Is there a way to circumvent the problem?
我可以写一个只包含RoleA、RoleB、RoleC"的常量——但我不喜欢魔术字符串,这是一个魔术字符串.更改角色的名称并忘记更改组合字符串将是一场灾难.
I COULD write a const which simply contains "RoleA,RoleB,RoleC" - but I dislike magic strings and this is a magic string. Changing the name of a Role and forgetting to change the combined string would be a disaster.
我正在使用 MVC5.ASP.NET 标识和角色在编译时已知.
I am using MVC5. ASP.NET Identity and the Role are known at compile time.
推荐答案
尝试创建自定义授权属性,如 这个.
Try to create custom authorize attribute like this.
public class AuthorizeRolesAttribute : AuthorizeAttribute
{
public AuthorizeRolesAttribute(params string[] roles) : base()
{
Roles = string.Join(",", roles);
}
}
假设多个控制器的角色相同,创建一个辅助类:
Assuming your roles will be the same for multiple controllers, create a helper class:
public static class Role
{
public const string Administrator = "Administrator";
public const string Assistant = "Assistant";
}
然后像这样使用它:
public class MyController : Controller
{
[AuthorizeRoles(Role.Administrator, Role.Assistant)]
public ActionResult AdminOrAssistant()
{
return View();
}
}
这篇关于多角色授权属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!