Fixing ValidationProblemDetails serialization Issues when using the JSON Source Generator in ASP.NET Core
As I gladly accept any kind of performance improvement I can get in my applications, I like to use the System.Text.Json source generator to generate the serialization logic for my Data Transfer Objects.
However after upgrading a project to .NET 8, I started to get errors.
The problem
When using ASP.NET Core's [ApiController]
attribute with automatic model validation, the framework automatically returns ValidationProblemDetails
objects for validation errors. However, if you've configured your application to use System.Text.Json
source generators for performance benefits, you might encounter serialization exceptions like:
System.NotSupportedException: JsonTypeInfo metadata for type 'Microsoft.AspNetCore.Mvc.ValidationProblemDetails' was not provided by TypeInfoResolver of type '[]'. If using source generation, ensure that all root types passed to the serializer have been annotated with 'JsonSerializableAttribute', along with any types that might be serialized polymorphically.
This occurs because the source generator doesn't have the necessary metadata to serialize ValidationProblemDetails
or ProblemDetails
at compile time.
Turns out I’m not the first one with this problem as I found more details in the following GitHub issue: `[ApiController]` attributes causes exception during serialization of `(Validation)ProblemDetails` when using source-generator-based serialization · Issue #57019 · dotnet/aspnetcore
A solution?
I couldn’t find a better solution, so I fixed it by explicitly adding the Validation types to my JsonSerializerContext:
I don’t know if this is the right solution. So if you know a better way, please let me know!
More information
Optimize your API performance with the System.Text.Json source generator