-
Notifications
You must be signed in to change notification settings - Fork 10.5k
Description
Background and Motivation
Recently, ASP.NET Core (MVC and Minimal APIs) were updated to use AOT/Trimmer-safe json serializer overloads. As part of this work a JsonOptions is pre-configured with a reflection-based resolver DefaultJsonTypeInfoResolver
| TypeInfoResolver = TrimmingAppContextSwitches.EnsureJsonTrimmability ? null : CreateDefaultTypeResolver() |
| TypeInfoResolver = TrimmingAppContextSwitches.EnsureJsonTrimmability ? null : CreateDefaultTypeResolver() |
While this change was correct, when it was applied, after the introduction of a new behavior to AddContext (dotnet/runtime#80527) all applications where TrimmingAppContextSwitches.EnsureJsonTrimmability is false won't use a source-gen context when calling AddContext since the DefaultJsonTypeInfoResolver was first added and the reflection-based resolver will be able to resolve any requested JsonTypeInfo.
Proposed API
My proposal is an introduction of a new IServiceCollection extension method AddDefaultHttpJsonOptions that will be responsible for make sure the right default configurations for Microsoft.AspNetCore.Http.Json.JsonOptions are set and in the appropriated order, eg.: PostConfiguration responsible for configure reflection-based resolver.
Also, to keep the behavior consistent I'm proposing an introduction of a new static getter Default that returns a cached/pre-configured default instance of Microsoft.AspNetCore.Http.Json.JsonOptions.
namespace Microsoft.Extensions.DependencyInjection;
public static class HttpJsonServiceExtensions
{
+ public static IServiceCollection AddDefaultHttpJsonOptions(this IServiceCollection services) {}
}
namespace Microsoft.AspNetCore.Http.Json;
public class JsonOptions
{
+ public static JsonSerializerOptions DefaultSerializerOptions { get; }
}Usage Examples
AddDefaultHttpJsonOptions
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDefaultHttpJsonOptions();
var app = builder.Build();
app.Run();Static default property
var typeInfo = JsonOptions.DefaultSerializerOptions.GetTypeInfo(typeof(string));
var json = JsonSerializer.Serialize("test", typeInfo);Alternative Designs
Risks
N/A