ASP.NET Core's default template adds RFC7807 Problem Details response to everything that results in 400: Bad Response:
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "00-3b3e118eb02dac41bcfc5d7c93509896-daaf187e081ea94e-00",
"errors": {
"Foo": [
"The Foo field is required."
]
}
}
(note that the field is Pascal cased, whereas JSON is usually camel-cased).
Other response statuses return an empty body. Wouldn't it be nice to receive a nice JSON response, regardless the HTTP status (ie 403, 404, 500 etc)?
Lucikly ASP.NET Core has a lot of extension points so this can be fixed relatively easily. You can write a custom middleware to catch all non-successful status codes and return a Problem Details response.
I've created a small NuGet package to configure the API for you: https://github.com/ProblemDetails/Problem.Details
After going through the installation and configuration process, all the non-successful HTTP responses should result in a nice and consistent JSON responses:
404 Not Found
{
"type": "https://httpstatuses.com/404",
"title": "Error: Not Found",
"status": 404
}
500 Internal Server Error
{
"type": "https://httpstatuses.com/500",
"title": "Error: Internal Server Error",
"status": 500,
"exception": "System.Exception: Testing 500\n at Sample.WebApi.Controllers.WeatherForecastController.Get(Int32 id) in /Users/hanneskarask/dev/Problem.Details/samples/Sample.WebApi/Controllers/WeatherForecastController.cs:line 42\n at lambda_method3(Closure , Object , Object[] )..."
}
(exception
field can be toggled programmatically, i.e. shown only locally)
400 Bad Request
{
"errors": {
"foo": ["The foo field is required."]
},
"type": "https://httpstatuses.com/400",
"title": "Error: Bad Request",
"status": 400
}
(fields are now camel-cased)
Currently there are a few configuration options:
- You can override the titles
.MapStatusToTitle(HttpStatusCode.BadRequest, "One or more validation errors occurred")
- Map custom exceptions
.MapException<NotFoundException>(HttpStatusCode.NotFound)