如何从ASP.NET MVC中的某些操作的Authorize Attribute获取角色数组?

Luc*_*ssi 5 asp.net asp.net-mvc authorization

假设我有以下控制器和具有授权属性的操作:

    public class IndexController : Controller
    {
        //
        // GET: /Index/

        [Authorize(Roles="Registered")]
        public ActionResult Index()
        {
            return View();
        }

    }
Run Code Online (Sandbox Code Playgroud)

我搜遍了整个互联网,但没有找到这个简单问题的答案:如何将角色注释到特定的动作/控制器?在这种情况下:索引操作有:string [] = {"Registered"}

Luc*_*ssi 5

最后我找到了解决方案!比我想象的更容易!ahahha我需要从AuthorizeAttribute扩展一个类并在动作中使用它.我需要的信息是继承类的属性"角色":

public class CustomAuthorizationAttribute : AuthorizeAttribute
{

    public override void OnAuthorization(AuthorizationContext filterContext)
    {

        var roles = this.Roles;

        base.OnAuthorization(filterContext);
    }

}
Run Code Online (Sandbox Code Playgroud)

在索引控制器上:

public class IndexController : Controller
    {
        //
        // GET: /Index/

        [CustomAuthorizationAttribute(Roles = "Registered")]
        public ActionResult Index()
        {
            return View();
        }

    }
Run Code Online (Sandbox Code Playgroud)