【问题标题】:POST request getting JSON value could not be converted to System.String. Path error获取 JSON 值的 POST 请求无法转换为 System.String。路径错误
【发布时间】:2021-10-11 22:57:57
【问题描述】:

我正在向 API 端点 http://localhost:20779/api/Account 发出 POST 请求并收到以下错误。

无法将 JSON 值转换为 System.String。路径:$ | 行号:0 | BytePositionInLine:1。”

这是我用来发出 POST 请求的 JSON。

{
    "EmailAddress": "hello@example.com",
    "Username": "example",
    "Password": "mypassword",
    "Status": "A",
    "CreatedOn": "2021-08-10 08:00:00"
}

请求命中 POST 方法。

namespace HelpDesk.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AccountController : ControllerBase
    {
        // POST api/<AccountController>
        [HttpPost]
        public void Post([FromBody] string value)
        {
            var x = string.Empty;
        }
  
    }
}

【问题讨论】:

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


    【解决方案1】:

    你必须创建一个视图模型类

    public UserViewModel
    {
    public string EmailAddress { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    public string Status { get; set; }
    public DateTime CreatedOn { get; set; }
    }
    

    并修复操作

     public IActionResult Post([FromBody] UserViewModel model)
    {
                return Ok(model.Username);
    }
    

    【讨论】:

      【解决方案2】:

      尝试将[FromBody] string value改为[FromBody] object content 然后如果你想读为字符串使用content.ToString()

      【讨论】:

        猜你喜欢
        • 2022-12-14
        • 2018-05-17
        • 2020-02-25
        • 2021-12-03
        • 2021-06-26
        • 1970-01-01
        • 1970-01-01
        • 2020-08-14
        • 2020-10-03
        相关资源
        最近更新 更多