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

后端 未结 2 1315
无人及你
无人及你 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: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);
    }
    

提交回复
热议问题