控制器上的动作过滤器,但仅在将另一个 ([HttpPost]) 应用于方法时才使用?

Fau*_*ust 5 asp.net-mvc action-filter

我想在控制器级别应用过滤器,但只有它的逻辑适用于直接具有 [HttpPost] 过滤器的操作方法。

也许可以从一个过滤器中检测另一个过滤器是否已应用于当前操作方法?

还是有其他方法可以达到我在第一句话中概述的效果?也许有一种扩展或替换 HttpFilter 的方法?

gdo*_*ica 5

我认为这就是你要找的:

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...                         
    }
}
Run Code Online (Sandbox Code Playgroud)