【问题标题】:ASP.NET Core MVC - Model Binding : Bind an interface model using the attribute [FromBody] (BodyModelBinder)ASP.NET Core MVC - 模型绑定:使用属性 [FromBody] (BodyModelBinder) 绑定接口模型
【发布时间】: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


    【解决方案1】:

    对于 C# 方法来说,使用接口很好,但是 MVC 需要知道在调用 Action 时它应该实例化什么具体类型,因为它正在创建它。它不知道要使用什么类型,因此无法将来自 Form/QueryString/etc 的输入绑定到。创建一个用于您的操作的非常基本的模型,它除了实现您的接口IOperator 之外什么都不做,如果您的目标是使其保持苗条,并将其设置为您的操作参数,它应该可以正常工作。

    我也尝试过在动作上使用接口,通过我自己的搜索,我发现除了使用类而不是接口来绑定之外没有其他方法可以让它工作。

    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);
    }
    

    【讨论】:

      猜你喜欢
      • 2018-08-30
      • 1970-01-01
      • 1970-01-01
      • 2022-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-27
      • 1970-01-01
      相关资源
      最近更新 更多