ASP.NET MVC ActionFilterAttribute在模型绑定之前注入值

我想创建一个自定义操作filter属性,在属性绑定期间可以访问的HttpContext项中添加一个值。

我试图在OnActionExecuting中添加它,但似乎模型绑定在filter之前被激活。

你知道我怎么做吗? 也许在模型绑定器中有一个方法我可以覆盖它将在filter之后触发并使用我的filter注入的值。

我想要做的是注入validation上下文(我用于validation的库支持上下文,它是nvalid.net(www.nvalid.net)

我希望能够放置一个属性,如

[ValidationContext("Prevalidation")] 

在我的actionresult方法上,以便我的自定义模型绑定器中发生的validation可以知道在执行validation时使用哪个上下文。

这就是我不能简单地制作自定义模型装订器的原因。

为什么不简单地编写自定义模型绑定器并在BindModel方法中工作?

我找到了实现它的方法。

 public class ModelBinder : DefaultModelBinder { protected override void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext) { var actionName = controllerContext.RouteData.Values["action"] != null ? controllerContext.RouteData.Values["action"].ToString() : string.Empty; var attribute = controllerContext.Controller.GetType().GetMethods() .Where(x => x.Name == actionName) .Where(x => x.GetCustomAttributes(false).Any(a => a.GetType() == typeof(CustomActionFilterAttribute))) .Select(x => x.GetCustomAttributes(typeof(CustomActionFilterAttribute), false).FirstOrDefault()) .FirstOrDefault() as CustomActionFilterAttribute; if(attribute != null && attribute.AnyProperty) { // Do what you want } } } 

通过reflection,我可以找到属性并在我的模型绑定器中使用它