我想從我的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。
任何幫助將不勝感激。
謝謝。
斷開的鏈接。這就是爲什麼我們不發佈僅鏈接的答案。 – brainbolt