C
C#6mo ago
nicke

Have all ControllerBase ObjectResults return StatusCodeResult with ProblemDetails

I'd like to unify the way errors are returned from my web api. With the introduction of AddProblemDetails this is pretty easy to do when a IAction returns a StatusCodeResult The problem is i have hunderds of places where I already return a ObjectResult for example BadRequest("foo") and this just creates a text/plain response instead of the desired ProblemDetails. Is there any clean way to achieve this in a clean way,? Or do i just need to override all usages of ObjectResult responses in ControllerBase?
4 Replies
nicke
nicke6mo ago
Some examples: return BadRequest() Returns a ProblemDetails with application/problem+json
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "Bad Request",
"status": 400,
"traceId": "00-84c1fd4063c38d9f3900d06e56542d48-85d1d4-00"
}
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "Bad Request",
"status": 400,
"traceId": "00-84c1fd4063c38d9f3900d06e56542d48-85d1d4-00"
}
While return BadRequest("foo") returns Foo with text/plain
nicke
nicke6mo ago
Never mind, this middleware seems to do everything i want https://github.com/khellang/Middleware/tree/master/src/ProblemDetails
GitHub
Middleware/src/ProblemDetails at master · khellang/Middleware
Various ASP.NET Core middleware. Contribute to khellang/Middleware development by creating an account on GitHub.
PixxelKick
PixxelKick6mo ago
I heavily try and avoid "exception catching" as a replacement for business logic. It obfuscates where things came from, it's a pain in the ass to debug (you'll get the exception caught and need to manually scan through its stack trace prop in the inner exception to figure out where it threw), and now you are at the whims of arbitry Try...Catch blocks that can ruin your system. I much prefer having an actual concrete defined TryResult<T> I actually can return from my methods and even mutate/append to as I bubble up.
nicke
nicke6mo ago
Yeah i know. The codebase is just massive and ported from net framework. The bigger issue was BadRequest("foo") returning a ObjectResult thats not automatically mapped to a ProblemDetail result while BadRequest() is