我希望在控制器级别应用一个过滤器,但只对直接使用了 [HttpPost] 过滤器的操作方法应用其逻辑。也许可以从一个过滤器中检测当前操作方法是否已应用另一个过滤器?或者还有其他实现我所述效果的方法吗?也许有一种方法可以扩展或替换 HttpFilter?
我认为这就是你要找的内容:
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...
}
}
好的,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);