Is there a way to get the DataAnnotation Errors rather than the JSON Parser Errors?
I have a model. Relevant fields, for example, are:
[RegularExpression(@"^(?i)(true|false)$", ErrorMessage = "{0} must be either 'true' or 'false'")]
public bool IsStudent { get; set; }
[Required]
[StringLength(50)]
[DataType(DataType.Text)]
[RegularExpression(@"^[A-Z]+[a-zA-Z\-]*$", ErrorMessage = "FirstName may only contain letters, numbers and dashes.")]
[Display(Name = "First Name")]
public string LastName { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
[Display(Name = "Date Started")]
public DateTime? DateStarted { get; set; }
My Controller:
[Route("api/[controller]")]
[ApiController]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public class PeopleController : Controller
{
//Removed for brevity
[Authorize]
[HttpPost("personupload")]
[ProducesResponseType(400)]
[ProducesResponseType(401)]
[ProducesResponseType(401)]
public IActionResult CreatePersonBatch([FromBody] IEnumerable<PersonImport> people)
{
//I understand this is not necessary
//Trying to see if it makes a difference. It does not.
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
// Goes on to create data table
}
}
When I send the following with Postman,
[
{
"LocationId": 0,
"RankId": 0,
"IsStudent": a,
"IsProspect": true,
"IsVendor": true,
"IsAppUser": true,
"FirstName": "string",
"LastName": "<Student>",
"BirthDate": "2021-03-14",
"Gender": "string",
"UniformTopSize": "string",
"UniformBottomSize": "string",
"BeltSize": "string",
"DateStarted": "now",
"DateLastAttended": "2021-03-14",
"IsHoh": true
}
]
I get the following response:
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "00-f2bde8fdc701de458f1d86297b7e4813-bdd66281fab85348-00",
"errors": {
"$[0].IsStudent": [
"The JSON value could not be converted to System.Boolean. Path: $[0].IsStudent | LineNumber: 4 | BytePositionInLine: 20."
]
}
}
It appears that the JSON Parser returns an unfriendly error message for the first error it encounters. I would like to return a list of friendly(ier) errors to API users as the DataAnnotation errors does. I can't seem to find out how to pre-empt the JSON Parser.