I'm developing a Web API in ASP.NET. When I use:
return BadRequest( result.Errors );
The response is just an array of errors. For consistency, I want the errors to be wrapped in the same wrapper as other asp.net errors like below:
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|803e532a-47325349ba863a12.",
"errors": {
"Password": [
"The Password field is required."
]
}
}
How to achieve this result?
CodePudding user response:
One of the simplest way is to return a
If we access the API method with valid data and add the custom model error, the result as below:
Besides, you can also create a custom ValidationError model which contains the returned fields, then try to use the action filter to handle the Validation failure error response. More detail information, please refer my reply in thread: I need to return customized validation result (response) in validation attributes in ASP.Net core Web API.