2015-08-28 80 views
1

我正在實現自定義模型綁定器。我研究瞭如何做到這一點,並發現在WebApi的情況下我需要實現IModelBinder接口。如何實現WebApi自定義模型綁定器

我的實現看起來是這樣的:

public class ModelBaseBinder : IModelBinder 
{ 
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) 
    { 
     if ((bindingContext.Model is MyModel)) 
     { 
      //my code here 

      controller.InitModel(model); 

      return true; 
     } 

     return false; 
    } 
} 

我只是不知道如果我的implenentaton完成。我是否需要調用任何默認的WebApi BindModel才能使我的自定義實現工作?

回答

0

我不確定這個實現,因爲我以前沒有嘗試過。我已應用於自定義模型綁定器的機制使用bindingContext.Model屬性將Model設置爲模型類的實例。 ex))。 bindingContext.Model = new Foo();

要讓自定義模型聯編程序在配置中運行,必須使用action參數旁邊的ModelBinder屬性,將模型聯編程序屬性應用於模型類或創建參數綁定規則。將模型綁定器屬性應用於動作方法參數爲使用模型綁定器添加了一些靈活性,並且是一種直接的方法

public IHttpActionResult FooAction([ModelBinder(BinderType=typeof(mymodelbinder))]Foo myFoo) { }