【问题标题】:Why is my post method not receiving the data that it is sent?为什么我的 post 方法没有收到它发送的数据?
【发布时间】:2018-03-27 10:46:44
【问题描述】:

我有一个post方法,参数School每次被调用时总是为null。我确保发送正确的数据,我使用的是 Postman,但是当我使用断点检查它时,我得到一个空对象。

我用 Postman 发送的内容:

{
    "Id": "",
    "Name": "Test"
}

控制器:

[HttpPost]
public IActionResult Post([FromBody] School school)
{
    try
    {
        if (!ModelState.IsValid)
        {
            return BadRequest();
        }

        var schoolData = Mapper.Map<School, Data.School>(school);

        var schoolModel = _schoolRepository.AddSchool(schoolData);

        return CreatedAtRoute("GetSchool", new { id = schoolModel }, schoolModel);
    }
    catch (Exception e)
    {
        return LogException(e);
    }
}

型号:

public class School
{
    public Guid Id { get; set; }
    [Required(ErrorMessage = "Name is required")]
    public string Name { get; set; }
    public IEnumerable<Teacher> Teachers { get; set; }
    public IEnumerable<Class> Classes { get; set; }
}

【问题讨论】:

  • 问题是"" 不是一个有效的Guid。如果您不想发送Id,请将其从模型绑定中排除
  • @CamiloTerevinto 是的,你是对的,我只是想,因为“Id”上没有必需的属性,它应该让它通过。您可以将此添加为答案并标记它

标签: c# http-post postman asp.net-core-webapi asp.net-core-2.0


【解决方案1】:

问题是您的模型需要Guid,而您发送的是empty string:

"Id": ""

不管Id 不是[Required],模型仍然无法解析数据。但是,您可以将其从绑定中排除:

public IActionResult Post([FromBody][Bind(Include = nameof(School.Name))] School school)

或者,更好的选择是使用 ViewModel。但是,在这种情况下,由于您只有一个属性,所以我只使用它:

public IActionResult Post([FromBody]string name)

【讨论】:

    猜你喜欢
    • 2012-06-11
    • 1970-01-01
    • 1970-01-01
    • 2023-01-27
    • 2021-06-03
    • 2020-11-16
    • 1970-01-01
    • 2017-07-06
    • 1970-01-01
    相关资源
    最近更新 更多