2016-04-08 87 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.... 
    } 
}