2017-07-26 70 views
1

我想從我的action方法中綁定一個接口模型,並將請求的內容類型是application/json。我在我的操作方法中使用[FromBody]屬性。ASP.NET Core MVC - 模型綁定:使用屬性綁定一個接口模型[FromBody](BodyModelBinder)

我試圖創建一個從ComplexTypeModelBinder派生的自定義modelBinder,通過以下鏈接:Custom Model Binding in Asp.net Core, 3: Model Binding Interfaces,但它不起作用,我的模型始終爲空。後來我學到了當你使用atribute [FromBody]時,BodyModelBinder被調用,內部調用JsonInputFormatter,它不使用自定義的modelBinder。

我正在尋找一種方法來綁定我的界面模型。我可以使用MVC DI來映射每個接口和它的實現。我的操作方法被定義爲:

public async Task<IActionResult> Create(IOperator user) 
    { 
     if (user == null) 
     { 
      return this.BadRequest("The user can't not be null"); 
     } 

     if (!this.ModelState.IsValid) 
     { 
      return this.BadRequest(this.ModelState); 
     } 

      IOperator op = await this.AuthenticationFrontService.CreateOperatorAsync(user.Login, user.Password, user.FirstName, user.LastName, user.ValidUntil, user.Role, user.Comment); 
     return new CreatedAtActionResult("Get", "operators", new { id = ((Operator)op).Id }, op); 
    } 

我試圖在我的接口使用MetadataType屬性的另一個解決方案,但它不能在命名空間System.ComponentModel.DataAnnotations存在,我讀了asp.net mvc的核心沒有按不使用此屬性Asp.Net MVC MetaDataType Attribute not working。我不想在域模型項目中安裝軟件包microsoft.aspnetcore.mvc.dataannotations以使用ModelDataType屬性。

我試着通過創建一個自定義的JsonInputFormater另一種解決方案,換句話說,我派生了JsonInputFormatter類,通過分析源代碼,我發現JsonSerializer無法反序列化一個邏輯上的接口。所以我正在尋找一個解決方案,我可以通過使用解析器或通用轉換器來定製jsonserializer。

任何幫助將不勝感激。

謝謝。

回答

0

對於C#方法使用接口是很好的,但MVC需要知道它在創建它時調用一個Action時應該實例化的具體類型。它不知道使用什麼類型,所以它不能將輸入從Form/QueryString/etc綁定到。創建一個非常基本的模型,用於你的動作,除了實現你的界面IOperator,如果你的目標是保持苗條,並將其設置爲Action參數,它應該可以正常工作。

我已經嘗試在動作上使用接口,並且通過我自己的搜索,我發現沒有辦法讓它工作,除了使用類而不是接口來綁定。

public class Operator : IOperator 
{ 
    //Implement interface 
} 

public async Task<IActionResult> Create(Operator user) 
{ 
    if (user == null) 
    { 
     return this.BadRequest("The user can't not be null"); 
    } 

    if (!this.ModelState.IsValid) 
    { 
     return this.BadRequest(this.ModelState); 
    } 

     IOperator op = await this.AuthenticationFrontService.CreateOperatorAsync(user.Login, user.Password, user.FirstName, user.LastName, user.ValidUntil, user.Role, user.Comment); 
    return new CreatedAtActionResult("Get", "operators", new { id = ((Operator)op).Id }, op); 
}