Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET 6 API populate extended ProblemDetails class with the default response values

I want to return all error responses in my API in the application/problem+json format. By default, returning an empty NotFound() or BadRequest() already results in this format. When they are passed values however (e.g. BadRequest("blah")), they lose this format.

Is there any way to return a ProblemDetails object with additional properties, without having to populate the default ProblemDetails properties by hand? I want to avoid using exception handlers for this, since I don't want to throw exceptions only for the sake of response formatting.

Response should look something like this:

{
  // should be auto-populated with values that an empty NotFound() generates
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.4",
  "title": "Not Found",
  "status": 404,
  "traceId": "00-7d554354b54a8e6be652c2ea65434e55-a453edeb85b9eb80-00",
  // what i want to add
  "additionalProperties": {
    "example": "blah"
  }
}
like image 913
M-Expunged Avatar asked Sep 18 '25 10:09

M-Expunged


1 Answers

You could use the ProblemDetailsFactory resolving it from DI to create an instance of a ProblemDetails. One of the parameters is the status code, and you can return from your action Problem(_factory.CreateProbelmDetails(…))

like image 90
Giacomo De Liberali Avatar answered Sep 20 '25 00:09

Giacomo De Liberali