Home > Software engineering >  .NET 6 API populate extended ProblemDetails class with the default response values
.NET 6 API populate extended ProblemDetails class with the default response values

Time:08-02

I want to return all error reponses 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 loose 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"
  }
}

CodePudding user response:

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(…))

  • Related