Iss*_*aji 5 model-binding asp.net-core-mvc asp.net-core
我想从我的操作方法绑定一个接口模型,并请求内容类型为 application/json。我在操作方法中使用 [FromBody] 属性。
我尝试通过以下链接创建从 ComplexTypeModelBinder 派生的自定义 modelBinder:Asp.net Core 中的自定义模型绑定,3:模型绑定接口,但它不起作用,我的模型始终为空。后来我了解到,当您使用属性 [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);
}
Run Code Online (Sandbox Code Playgroud)
我通过在界面中使用 MetadataType 属性尝试了另一种解决方案,但它在命名空间 System.ComponentModel.DataAnnotations 中不存在,并且我读到 asp.net core mvc does not use this attribute Asp.Net MVC MetaDataType Attribute not working。我不想在域模型项目中安装包 microsoft.aspnetcore.mvc.dataannotations 来使用 ModelDataType 属性。
我通过创建自定义 JsonInputFormater 尝试了另一种解决方案,换句话说,我派生了 JsonInputFormatter 类,并通过分析源代码,我发现 JsonSerializer 无法反序列化逻辑接口。所以我正在寻找一个解决方案,我可以通过使用解析器或通用转换器来自定义 jsonserializer。
任何帮助将不胜感激。
谢谢。
对于 C# 方法来说,使用接口很好,但是 MVC 在创建 Action 时需要知道它应该实例化什么具体类型。它不知道要使用什么类型,因此它无法将来自 Form/QueryString/etc 的输入绑定到。创建一个非常基本的模型以在您的操作中使用,该模型除了实现您的界面之外什么也不做IOperator,如果您的目标是保持它的苗条,并将其设置为您的操作参数,它应该可以正常工作。
我也尝试过在操作上使用接口,通过我自己的搜索,我发现除了使用类而不是接口来绑定之外,没有办法让它工作。
public class Operator : IOperator
{
//Implement interface
}
Run Code Online (Sandbox Code Playgroud)
。
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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6125 次 |
| 最近记录: |