You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

POST请求多对象处理:API接收CustomerDto遇400错误求助

问题排查与解决方案

一、代码中的核心错误

  • 类型不匹配与大小写问题:API方法返回ActionResult<VillaDTO>(与业务无关的错误类型),同时参数CustomerDTO的大小写和类定义CustomerDto不一致(C#严格区分大小写),直接导致模型绑定失败。
    修正后的方法签名:

    public ActionResult<CustomerDto> AddCustomer([FromBody] CustomerDto customerDto)
    
  • 变量引用错误:判断customerDto == null时返回BadRequest(villaDTO),villaDTO未定义,属于复制粘贴失误,修正为:

    if (customerDto == null)
    {
        return BadRequest();
    }
    
  • 批量需求未匹配:你需要提交多个Customer对象,但当前API仅接收单个对象。若要实现批量新增,需修改参数为列表类型:

    [HttpPost("batch")]
    public ActionResult<List<CustomerDto>> AddCustomers([FromBody] List<CustomerDto> customerDtos)
    {
        if (customerDtos == null || !customerDtos.Any())
        {
            return BadRequest("未提供客户数据");
        }
        
        CustomerService.customerList.AddRange(customerDtos);
        return Ok(customerDtos);
    }
    

二、PostMan请求的正确配置

单个Customer提交

  1. 请求方法选POST,URL填写你的API地址(如https://localhost:5001/api/customers)
  2. Headers添加Content-Type: application/json
  3. Body选择raw,格式切换为JSON,输入:
    {
      "Id": 4,
      "FirstName": "Alice"
    }
    

多个Customer批量提交

如果使用上面的批量新增接口,Body的JSON格式应为数组:

[
  {
    "Id": 4,
    "FirstName": "Alice"
  },
  {
    "Id": 5,
    "FirstName": "Bob"
  }
]

三、错误信息解析

  • "The JSON value could not be converted to CustomerDto":多数是JSON格式与接口接收类型不匹配(比如提交数组但接口只接收单个对象,或字段名拼写/大小写错误)
  • "The customerDTO field is required":因为参数名customerDTO与类名CustomerDto大小写不一致,模型绑定无法识别,修正参数名后即可解决。

内容的提问来源于stack exchange,提问作者user3920526

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 12:10:20