Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return response in default wrapper

Tags:

asp.net-core

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?

like image 993
Dominik Mistera Avatar asked May 02 '26 10:05

Dominik Mistera


1 Answers

One of the simplest way is to return a ValidationProblemDetails:

ModelState.AddModelError("Password", "Password field is required");
return ValidationProblem(ModelState);

Or

return ValidationProblem(new ValidationProblemDetails(
    new Dictionary<string, string[]>
    {
        {"Password", new[] {"Password field is required."}}
    }));
like image 87
weichch Avatar answered May 04 '26 01:05

weichch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!