0

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;
        }
  
    }
}
Serge
  • 40,935
  • 4
  • 18
  • 45
Red Virus
  • 1,633
  • 3
  • 25
  • 34
  • Does this answer your question? [ASP.NET Core 3.0 \[FromBody\] string content returns "The JSON value could not be converted to System.String."](https://stackoverflow.com/questions/58150652/asp-net-core-3-0-frombody-string-content-returns-the-json-value-could-not-be) – Ian Kemp Dec 17 '22 at 20:41

2 Answers2

1

Try to change [FromBody] string value to [FromBody] object content and then if you want to read as string use content.ToString()

1

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);
}
Serge
  • 40,935
  • 4
  • 18
  • 45