授权,多个角色属性 [英] Authorize Attribute with Multiple Roles
问题描述
我想授权一次添加到控制器,支持多种角色。
I would like to add Authorization to a controller, for multiple Roles at once.
通常情况下,将是这样的:
Normally that would look like this:
[Authorize(Roles = "RoleA,RoleB,RoleC")]
public async Task<ActionResult> Index()
{
}
但我已经存储在我的角色在consts,因为他们可能会改变或在某些时候进行扩展。
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一个const - 但是我不喜欢魔术字符串,这是一个神奇的字符串。更改角色名称和遗忘改变组合的字符串将是一场灾难。
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.
推荐答案
尝试创建自定义的授权像<一个属性href=\"http://tech-journals.com/jonow/2011/05/19/avoiding-magic-strings-in-asp-net-mvc-authorize-filters\">this.
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";
}
然后使用它像这样:
Then use it like so:
public class MyController : Controller
{
[AuthorizeRoles(Role.Administrator, Role.Assistant)]
public ActionResult AdminOrAssistant()
{
return View();
}
}
这篇关于授权,多个角色属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!