Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 475
Faust Avatar asked Oct 09 '22 08:10

Faust


1 Answers

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...                         
    }
}
like image 187
gdoron is supporting Monica Avatar answered Oct 18 '22 00:10

gdoron is supporting Monica