2016-04-08 80 views
3

我在的WebAPI的自定义模型绑定使用以下方法从`Sytem.Web.Http.ModelBinding”命名空间,其有关Web API创建自定义模型绑定正确的命名空间:如何从WebAPI中的自定义绑定器调用默认模型绑定?

public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) 
{ 

} 

我在控制器上有一个HTTP POST,我想使用这个自定义模型活页夹。发布的对象大约包含100个字段。我想改变其中的2个。我需要的是默认模型绑定发生,然后操纵这两个字段的模型绑定对象,以便一旦控制器收到对象,它就是原始的。

问题是我似乎无法模型绑定我的对象使用上面的模型绑定方法的默认绑定。在MVC有以下几点:

base.BindModel(controllerContext, bindingContext);

同样的方法的确在的WebAPI 工作。也许我正在讨论这个错误,还有另一种方法来实现我想要的,所以请建议如果自定义模型联编程序不是正确的方法。我试图阻止做的是不得不操纵控制器内张贴的对象。我可以在技术上这样做后,它已被模型绑定,但我想在调用堆栈中这样做,以便控制器不需要担心这两个字段的自定义操作。

如何在我的自定义模型联编程序中启动对bindingContext的默认模型绑定,以便我拥有一个完全填充的对象,然后我可以在返回之前操纵/按摩我需要的最后2个字段?

回答

0

在WebApi中,'默认'模型联编程序是CompositeModelBinder,它包装所有注册的模型联编程序。如果你想重新使用它的功能,你可以这样做:

public class MyModelBinder : IModelBinder 
{ 
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) 
    { 
     if (bindingContext.ModelType != typeof(MyModel)) return false; 

     //this is the default webapi model binder provider 
     var provider = new CompositeModelBinderProvider(actionContext.ControllerContext.Configuration.Services.GetModelBinderProviders()); 
     //the default webapi model binder 
     var binder = provider.GetBinder(actionContext.ControllerContext.Configuration, typeof(MyModel)); 

     //let the default binder do it's thing 
     var result = binder.BindModel(actionContext, bindingContext); 
     if (result == false) return false; 

     //TODO: continue with your own binding logic.... 
    } 
}