How to efficiently test if action is decorated with an attribute (AuthorizeAttribute)?

后端 未结 2 1314
无人及你
无人及你 2021-02-02 15:02

I\'m using MVC and have a situation where in my OnActionExecuting() I need to determine if the Action method that is about to execute is decorated with an attribute

相关标签:
2条回答
  • 2021-02-02 15:29

    var hasAuthorizeAttribute = filterContext.ActionDescriptor.IsDefined(typeof(AuthorizeAttribute), false);

    http://msdn.microsoft.com/en-us/library/system.web.mvc.actiondescriptor.isdefined%28v=vs.98%29.aspx

    0 讨论(0)
  • 2021-02-02 15:43

    You can simply use filterContext.ActionDescriptor.GetCustomAttributes

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        bool hasAuthorizeAttribute = filterContext.ActionDescriptor
            .GetCustomAttributes(typeof(AuthorizeAttribute), false)
            .Any();
    
        if (hasAuthorizeAttribute)
        { 
            // do stuff
        }
    
        base.OnActionExecuting(filterContext);
    }
    
    0 讨论(0)
提交回复
热议问题