`TypedResults.ValidationProblem` doesn't serialize the `errors` property if `AddProblemDetails` is called after `AddControllers`
- Dominant language
- C#
- Stars
- 38.4k
- Forks
- 10.9k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 281
Description
### Is there an existing issue for this?
- [x] I have searched the existing issues
### Describe the bug
If you have an API controller that returns `TypedResults.ValidationProblem` then the JSON that is serialized from that result is missing the `errors` property if the startup code called `builder.Services.AddProblemDetails()` **after** `builder.Services.AddControllers()`.
### Expected Behavior
A JSON that is serialized from `TypedResults.ValidationProblem` from an API controller method should always contain the `errors` property.
### Steps To Reproduce
1. Create a new ASP.NET Core Web API project with "Use controllers" enabled.
2. Change `WeatherForecastController.Get` to:
```cs
public IResult Get()
{
return TypedResults.ValidationProblem([new KeyValuePair("Test", ["This is a validation error."])]);
}
```
3. Call the API. Note that the `errors` property is correctly returned.
4. Add `builder.Services.AddProblemDetails();` **after** `builder.Services.AddControllers();`
5. Call the API. Note that the error is now missing.
6. Move `builder.Services.AddProblemDetails();` **before** `builder.Services.AddControllers();`
7. Call the API. Note that the error is correctly returned again.
### Exceptions (if any)
_No response_
### .NET Version
10.0.301
### Anything else?
ASP.NET Core version: 10.0.9
The reason for this bug seems to be explained in https://github.com/dotnet/aspnetcore/issues/59052#issuecomment-2573987430. In my opinion that issue shouldn't have been closed.
According to https://github.com/dotnet/aspnetcore/issues/59052#issuecomment-2700992760 the same problem happens with `AddApiVersioning`.
This is especially bad because documentation pages (like [this one](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/error-handling)) show sample code where the order of calls will trigger this bug.
Contributor guide
Research direction
Start with the WeatherForecastController.Get reproduction and compare the serialized TypedResults.ValidationProblem response with AddControllers and AddProblemDetails registered in each order. Trace the interaction between TypedResults.ValidationProblem, AddProblemDetails, and controller registration; done means the JSON always includes errors regardless of registration order, including the documented sample order.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- csharp
- Domain
- api, backend
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Quiet
- Clarity
- Mostly clear
- Newbie friendliness
- 55/100