POST 获取 JSON 值的请求无法转换为 System.String。路径错误

POST request getting JSON value could not be converted to System.String. Path error

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

The JSON value could not be converted to System.String. Path: $ | LineNumber: 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;
        }
  
    }
}

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

您必须创建视图模型class

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);
}