Search code examples
asp.net-mvcaction-filter

Action Filters on Controller, but only used if another ([HttpPost]) is applied to method?


I'd like to apply a filter at the Controller level, but only have it's logic apply to action-methods that have the [HttpPost] filter on them directly.

Perhaps it is possible to detect from within one filter whether another filter has been applied on the current action method?

Or is there another way of achieving the effect I outlined in my first sentence? Perhaps there is a way of extending or replacing the HttpFilter?


Solution

  • I think this is what you are looking for:

    public class PostActiongFilter : ActionFilterAttribute
    {
        public virtual void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var actionName = filterContext.ActionDescriptor.ActionName;
            var actionParams = filterContext.ActionDescriptor.GetParameters
            var actionParamsTypes = actionParams.Cast<ParameterDescriptor>()
                                          .Select(x => x.ParameterType).ToArray();
            var controllerType = filterContext.Controller.GetType();            
            var actionMethodInfo = controllerType.GetMethod(actionName,
                                                            actionParamsTypes, null);            
            var isMethodPost = actionMethodInfo.IsDefiend(typeof(HttpPostAttribute),
                                                          false);
    
            if (!isMethodPost)
                return;
    
            // Do what you want for post here...                         
        }
    }