I get an inconsistent behaviour when asp.net core api validates objects and when I manually add model errors and invoke BadRequest(ModelState)
As an example, I have these 2 endpoints in my controller
[HttpPost]
public IActionResult Post(MyModel model)
{
return Ok();
}
[HttpPost]
[Route("test")]
public IActionResult OtherPost()
{
ModelState.AddModelError("field", "error");
return BadRequest(ModelState);
}
and MyModel is:
public class MyModel
{
[Required]
[MinLength(10)]
public string MyProperty { get; set; }
}
When I invoke the first endpoint with an empty body I don't need to validate ModelState because the framework is going to do it automatically and gives this response:
{
"errors":{"MyProperty":["The MyProperty field is required."]},
"title":"One or more validation errors occurred.",
"status":400,
"traceId":"80000005-0000-ff00-b63f-84710c7967bb"
}
With the second controller I get this:
{"field":["error"]}
Am I using the wrong method to add errors to ModelState or it is an known problem?