2010-11-24 50 views
6

我想创建一个自定义操作过滤器属性,该属性在模型绑定期间可以访问的HttpContext项目中添加一个值。ASP.NET MVC ActionFilterAttribute在模型绑定之前注入值

我试图将它添加到OnActionExecuting中,但它似乎在过滤器之前执行了模型绑定。

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

我想要做什么,是注入验证上下文(我使用的验证库支持背景下,nvalid.net(www.nvalid.net)

我希望能够把属性如

[ValidationContext("Prevalidation")] 

我的ActionResult方法,使发生在我的自定义模型绑定验证才能知道做验证时使用的上下文。

这就是为什么我不能简单地做一个自定义模型绑定器。

回答

3

为什么不简单地写一个自定义模型联编程序并在BindModel方法中工作?

4

我找到了一种方法来实现它。

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

反射我能找到的属性,并在我的模型绑定器使用它