[英]POST request getting JSON value could not be converted to System.String. Path error
I'm making a POST request to API endpoint http://localhost:20779/api/Account and getting the following error.我正在向 API 端点http://localhost:20779/api/Account发出 POST 请求并收到以下错误。
The JSON value could not be converted to System.String.
无法将 JSON 值转换为 System.String。 Path: $ |
路径:$ | LineNumber: 0 |
行号:0 | BytePositionInLine: 1."
BytePositionInLine:1。
This is the JSON I'm using to make POST request.这是我用来发出 POST 请求的 JSON。
{
"EmailAddress": "hello@example.com",
"Username": "example",
"Password": "mypassword",
"Status": "A",
"CreatedOn": "2021-08-10 08:00:00"
}
The request hits the POST method.请求命中 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;
}
}
}
Try to change [FromBody] string value
to [FromBody] object content
and then if you want to read as string use content.ToString()
尝试将
[FromBody] string value
更改为[FromBody] object content
,然后如果要读取为字符串,请使用content.ToString()
you have to create a view model 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; }
}
and fix the action并修复动作
public IActionResult Post([FromBody] UserViewModel model)
{
return Ok(model.Username);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.