首页 > 解决方案 > Core Web Api - 错误:动作从请求正文绑定了多个参数

问题描述

[ApiController]
[Route("test")]
public class AdminController : ControllerBase
{
    [HttpPost]
    public IActionResult Create(CarModel car, int[] customers, int model)
    {
        var item = new Car()
        {
            Name = car.Name,
            Price = car.Price
        };
        repository.Create(item, customers, model)
        return Ok(item);
    }
}

车类

public int Id { get; set; }
public string Name{ get; set; }
public int Price{ get; set; }

汽车模型

public int Id { get; set; }
public string Name{ get; set; }
public int Price{ get; set; }}

我可以将“客户”和“模型”参数添加到我的“汽车”类中。但我不想在我的“汽车”类中添加“客户”和“模型”参数

我怎样才能以其他方式解决这个问题。

错误 在此处输入图像描述

标签: c#asp.net-core.net-coreasp.net-web-apiasp.net-core-webapi

解决方案


如果您从请求正文中发布所有这些输入参数,则必须创建 ViewModel:

 public class CarViewModel
{
public CarModel car {get; set;} 
public int[] customers {get; set;}
public int model {get; set;}
}

但我认为你不需要所有这些属性,你可以合并一些。

改变你的行动:

public IActionResult Create(CarViewModel model)
//or you can try, I don't know how you call your action
public IActionResult Create([FromBody] CarViewModel model)

将视图中的模型替换为:

@model CarViewModel

并修复您的视图控件数据绑定


推荐阅读