khellang / Middleware

Various ASP.NET Core middleware
MIT License
811 stars 112 forks source link

AddNewtonsoftJson and ProblemDetails using NET 6 #200

Open wzaieddev opened 1 year ago

wzaieddev commented 1 year ago

Hi, I still having the same problem as (https://github.com/khellang/Middleware/issues/74 )

I'am having problems using Newtonsoft as the json serializer with problem details. When this package returns the problem details the Extensions property is serialzied as "Extensions": {...} and not to the parent.

My Web API is built withNET 6 i'm using Hellang.Middleware.ProblemDetails vs 6.5.1

example of response { "error": { "code": "xxxxxxx", "message": "TEST EXCEPTION" }, "type": "https://httpstatuses.io/422", "title": "Bad Request", "status": 422, "detail": null, "instance": "/api/v2/", "extensions": { "traceId": "00-c7eeff3ccf1f649acb783983201da96d-b6eab3d064ab8984-00", "timestamp": "2023-09-21T20:14:36.2960678+02:00" } } when I JSON serializer xx the problem does not arise, and the response is like this

{ "error": { "code": "xxxxxxx", "message": "TEST EXCEPTION" }, "type": "https://httpstatuses.io/422", "title": "Bad Request", "status": 422, "detail": null, "instance": "/api/v2/", "traceId": "00-c7eeff3ccf1f649acb783983201da96d-b6eab3d064ab8984-00", "timestamp": "2023-09-21T20:14:36.2960678+02:00"

}

is there any solution to keep using Newtonsoft ?

kirodge commented 1 year ago

I had the same issue when I used the constructor of StatusCodeProblemDetails var problemDetails = new StatusCodeProblemDetails(StatusCodes.Status409Conflict);

Replacing this with a call to the factory method that returns Mvc.ProblemDetails resolved the issue for me var problemDetails = StatusCodeProblemDetails.Create(StatusCodes.Status409Conflict);

My guess is that the ProblemDetailsJsonConverter, which is applied through the JsonConverter attribute on Mvc.ProblemDetails, does not apply to the subclass StatusCodeProblemDetails.