Description
We are converting some old NET framework MVC APIs over to using NET 8. One of the issues we are facing is that the formatting of the bad request has changed.
In Framework this used to look like this
{
"Message": "The request is invalid.",
"ModelState": {
"item": [
"Required property 'Name' not found in JSON. Path '', line 1, position 14."
],
"item.Name": [
"The Name field is required."
],
"item.Price": [
"The field Price must be between 0 and 999."
]
}
}
However, in NET 8 the bad response follow RFC 7807.
{
"type": "https://tools.ietf.org/html/rfc9110#section-15.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"errors": {
"Denominator": [
"'Denominator' must not be equal to '0'."
]
},
"traceId": "00-150bc955d10cdf2cdb3c68546ca8d144-a4fc961af95051c4-00"
}
Unfortunately, we need keep the old format and cannot use RFC 7807 for our responses. Is there any property we can set to restore the old format?
The other approach we have attempted is to reformat the RFC 7807 back to the old using a custom IProblemDetailsWriter but the documentation isn't very clear on how to inject this correctly.
We taken a look at the sample project here but we noticed that in this sample project when using the #define SampleProblemDetailsWriter it is using app.Map() it works via define an earlier middleware that overwrites the response. Because we are using MVC with
controllers we were interested in the #define API_CONTROLLER sample. We notice that if we replace the
builder.Services.AddProblemDetails();
with our custom implication using
builder.Services.AddTransient<IProblemDetailsWriter, SampleProblemDetailsWriter>();
The web application was not making using our implementation of the IProblemDetailsWriter. We then tried to add another middleware that would overwrite the response, however this results in a
System.InvalidOperationException: Headers are read-only, response has already started.
Is there a recommended way to restore the older format that was returned in NET Framework when the Model Validation fails in NET8?
We did notice that after calling AddControllers()
there are 2 IProblemDetailWriters
We suspect that the controllers are using the DefaultApiProblemDetailsWriter
instead of the implementation that we have added to the DI container.
Are we going with the right approach trying to overwrite the IProblemDetailsWriter or should another method be attempted?