Search code examples
c#asp.net.net-corewebapiasp.net-core-5.0

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.

The JSON value could not be converted to System.String. Path: $ | LineNumber: 0 | BytePositionInLine: 1."

This is the JSON I'm using to make POST request.

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

The request hits the POST method.

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

Solution

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