C# MVC5 ASP身份动态授权属性

C# MVC5 ASP身份动态授权属性,c#,asp.net-mvc,authorization,asp.net-identity,authorize-attribute,C#,Asp.net Mvc,Authorization,Asp.net Identity,Authorize Attribute,我有一个带有后端的MVC5项目来配置哪个角色可以访问哪个菜单。实现基于角色的授权的一般方法如下所示 [Authorize(Roles="Admin")] public ActionResult UpdateProduct(ProductModel model) { //do something return View(model); } [Authorize(Roles=GetRoles("UpdateProduct"))] public ActionResult Upda

我有一个带有后端的MVC5项目来配置哪个角色可以访问哪个菜单。实现基于角色的授权的一般方法如下所示

[Authorize(Roles="Admin")]
public ActionResult UpdateProduct(ProductModel model)
{
     //do something
     return View(model);
}
[Authorize(Roles=GetRoles("UpdateProduct"))]
public ActionResult UpdateProduct(ProductModel model)
{
     //do something
     return View(model);
}
因为我需要角色是动态的,所以我想到了这样的事情

[Authorize(Roles="Admin")]
public ActionResult UpdateProduct(ProductModel model)
{
     //do something
     return View(model);
}
[Authorize(Roles=GetRoles("UpdateProduct"))]
public ActionResult UpdateProduct(ProductModel model)
{
     //do something
     return View(model);
}
显然,它不起作用,因为属性是静态元数据

我环顾四周,发现了这一点,但有没有更干净的方法来实现这一点


注意:我试图避免在每个方法中调用
User.IsInRole

C中代码属性的定义是它是静态的-因此不能有一个方法,
GetRoles()

您建议使用以下属性:

[Authorize(Roles=GetRoles(“UpdateProduct”))]

这意味着您必须在代码中实现
GetRoles()
,因此请使用从
Authorize
派生的自定义属性

    public class CustomAuthorizeAttribute : AuthorizeAttribute
    {

        public CustomAuthorizeAttribute(string roleSelector)
        {

            Roles = GetRoles(roleSelector);
        }

        private string GetRoles(string roleSelector)
        {
            // Do something to get the dynamic list of roles instead of returning a hardcoded string
            return "Somerole";
        }
}
现在你可以做:

[客户授权(“更新产品”)]