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

5
我希望在控制器级别应用一个过滤器,但只对直接使用了 [HttpPost] 过滤器的操作方法应用其逻辑。也许可以从一个过滤器中检测当前操作方法是否已应用另一个过滤器?或者还有其他实现我所述效果的方法吗?也许有一种方法可以扩展或替换 HttpFilter?
2个回答

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...                         
    }
}

1
你上一行有错误:var isMethodPost = actionMethodInfo.IsDefined(typeof(HttpPostAttribute), false); - Ryk
1
@Ryk,谢谢。顺便说一下,这个网站允许您在需要时进行编辑或建议编辑。无论如何,你说得很对。 - gdoron

-1

好的,HttpPostAttribute是被密封的。但你可以通过查看它(ILSpy是你的朋友)来获取灵感:

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class HttpPostAttribute : ActionMethodSelectorAttribute
{
    private static readonly AcceptVerbsAttribute _innerAttribute = new AcceptVerbsAttribute(HttpVerbs.Post);
    public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
    {
        return HttpPostAttribute._innerAttribute.IsValidForRequest(controllerContext, methodInfo);
    }
}

很简单吧?你只需要创建完全相同的逻辑,然后返回即可

return (yourCustomCondition) && HttpPostAttribute._innerAttribute.IsValidForRequest(controllerContext, methodInfo);

1
这个答案并不是一个通用解决方案,因为 HttpPost 属性的内部逻辑可能会在更高版本的 MVC 中发生变化,那么这个解决方案就会失效。在这种情况下,@gdoron 提供的答案要好得多。 - Anton

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接