【问题标题】:The Input was not valid输入无效
【发布时间】:2018-10-10 01:41:25
【问题描述】:

从 Postman 调用 apiController 方法时,我遇到了问题。

Postman 客户端调用下面方法中提到的带参数的方法

    [AllowAnonymous]
    [HttpPost]
    public IActionResult Register([FromBody]UserDto userDto)
    {
        // map dto to entity
        //var user = _mapper.Map<User>(userDto);
        return Ok(new
        {
            userDto
        });

        //try
        //{
        //    // save 
        //    _userService.Create(user, userDto.Password);
        //    return Ok();
        //}
        //catch (AppException ex)
        //{
        //    // return error message if there was an exception
        //    return BadRequest(new { message = ex.Message });
        //}
    }

映射 UserDto..

public class UserDto
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
}

但我得到以下错误:

【问题讨论】:

  • FromBody 用于 JSON 数据。您正在传递表单数据。这些不兼容。在 Postman 中使用 Body > Raw 并将 JSON 放在那里。否则,请使用更合适的工具,例如 Swagger
  • 仅供参考...这确实是一个邮递员的问题。
  • 如果你必须使用表单数据编码,你也可以使用[FromForm]而不是FromBody。我相信如果您完全跳过该属性,它也会推断出这一点。
  • @CamiloTerevinto:也这样做了[{“Id”:1,“FirstName”:“Jason”,“LastName”:“Bond”,“用户名”:“Jason”,“密码”: “你好”}].. 相同的结果
  • @Jason 那是因为您的方法设置为接收单个实体,而您只是尝试传递实体数组。

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


【解决方案1】:

使用 raw 选项并从下拉列表中选择 json 并在正文中添加您的 dto 值。

原始

{
"FirstName" : "yourname",
"LastName": "lastname"
}

【讨论】:

  • 这仅适用于我输入的临时代码。对于实际代码,它似乎有些例外..**info: Microsoft.AspNetCore.Server.Kestrel[32] Connection id "0HLHE2K4LHFNC", Request id "0HLHE2K4LHFNC:00000001": the application completed without reading the entire request body.**
猜你喜欢
  • 2013-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-06
相关资源
最近更新 更多