【问题标题】:Core Web Api - Error: Action has more than one parameter bound from request bodyCore Web Api - 错误:动作从请求正文绑定了多个参数
【发布时间】:2021-04-22 19:32:07
【问题描述】:
[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; }}

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

我该如何通过其他方式解决这个问题。

错误

【问题讨论】:

  • 你能展示你的汽车课吗?我不明白有什么问题。为什么要在输入参数中放入 int[] customers, int model?
  • 报错信息明确指出请求体中只能绑定一个参数,同时也提供了可以遵循的替代方案。
  • @Sergey 我更新了代码。我附上了错误消息的屏幕截图。
  • @Nkosi 我不能让这个无效吗?不能传2个参数?
  • 不,您不能使其无效。这就是框架的设计方式。所有这些参数都预计来自请求正文吗?是否有任何来自 URL?参考Model Binding in ASP.NET Core

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


【解决方案1】:

如果您从请求正文中发布所有这些输入参数,则必须创建 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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-19
    • 1970-01-01
    • 1970-01-01
    • 2021-09-01
    • 1970-01-01
    • 2013-12-25
    • 2014-03-22
    • 1970-01-01
    相关资源
    最近更新 更多