【发布时间】:2018-01-02 01:38:33
【问题描述】:
我想将我的操作方法中的接口模型与内容类型为 application/json 的请求绑定。我在我的操作方法中使用了 [FromBody] 属性。
我尝试通过以下链接创建从 ComplexTypeModelBinder 派生的自定义 modelBinder:Custom Model Binding in Asp.net Core, 3: Model Binding Interfaces,但它不起作用,我的模型始终为空。之后我了解到,当您使用属性 [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 core mvc 不使用此属性Asp.Net MVC MetaDataType Attribute not working。我不想在域模型项目中安装包 microsoft.aspnetcore.mvc.dataannotations 以使用 ModelDataType 属性。
我通过创建自定义 JsonInputFormater 尝试了另一种解决方案,换句话说,我派生了 JsonInputFormatter 类,并且通过分析源代码,我发现 JsonSerializer 无法反序列化一个合乎逻辑的接口。所以我正在寻找一种解决方案,我可以通过使用解析器或通用转换器来自定义 jsonserializer。
任何帮助将不胜感激。
谢谢。
【问题讨论】:
标签: asp.net-core asp.net-core-mvc model-binding