I have a simple class for the POST request body:
[Route("api/[controller]")]
[ApiController]
public class TestController : ControllerBase
{
[HttpPost]
public IActionResult Post(PostRequest request)
{
return Ok();
}
}
public class PostRequest
{
[Required]
public String String { get; set; }
}
If I send an int instead of a string, the following error message is returned:
"$.string": [
"The JSON value could not be converted to System.String. Path: $.string | LineNumber: 1 | BytePositionInLine: 13."] }
I don’t feel like exposing what happens under the hood is right. Is there a way to return a generic "The field String is invalid" message?
2
Answers
I’m not sure, but maybe this will help you. Paste this code at the very beginning of the method:
This error comes from
System.Text.Json.JsonSerializer
inside SystemTextJsonInputFormatter durring desrializing request body into the model and you can disable it like below:And you will relieve error message like this:
You can also customize error message and get rid of
$.
like below: