In an ASP.NET Core 10 Native AOT Minimal API, why is a JsonSerializerContext inserted at index 0 of TypeInfoResolverChain, and what happens to a type you forgot to list?
answer
- [JsonSerializable(typeof(T))] per root type
- partial class deriving from JsonSerializerContext
- resolvers are asked in chain order
- no reflection fallback when trimmed
- anonymous types cannot be listed
basics
~20 sNative AOT cannot serialize JSON by reflection, so every body type needs source-generated metadata from a JsonSerializerContext. Index 0 makes it the first resolver asked. A type missing from the context has no metadata, so the native app throws at run time.
solid answer
~40 sIn a trimmed or Native AOT app, reflection-based System.Text.Json is off by default, and ASP.NET Core's `JsonOptions` then start with an empty resolver instead of the reflection-based `DefaultJsonTypeInfoResolver`. So every type a Minimal API reads from or writes to a body needs **source-generated metadata**: a `partial` class deriving from `JsonSerializerContext` with one `[JsonSerializable(typeof(T))]` per root type. The `webapiaot` template registers it with `ConfigureHttpJsonOptions(o => o.SerializerOptions.TypeInfoResolverChain.Insert(0, AppJsonSerializerContext.Default))`. Resolvers in the chain are asked in order and the first that returns metadata wins, so index 0 puts your generated metadata ahead of anything already there. A type you forgot, or an anonymous type, has no metadata, so the native app throws when that endpoint serializes it, even if JIT-hosted integration tests, where reflection stays enabled, passed.
code
csharp · 20 linesusing System.Text.Json.Serialization;
var builder = WebApplication.CreateSlimBuilder(args);
builder.Services.ConfigureHttpJsonOptions(options =>
options.SerializerOptions.TypeInfoResolverChain.Insert(0, AppJsonSerializerContext.Default));
var app = builder.Build();
app.MapPost("/resize", (ResizeRequest request) =>
TypedResults.Ok(new ResizeResult(request.ImageId, request.Width, request.Height)));
app.Run();
public record ResizeRequest(string ImageId, int Width, int Height);
public record ResizeResult(string ImageId, int Width, int Height);
[JsonSerializable(typeof(ResizeRequest))]
[JsonSerializable(typeof(ResizeResult))]
internal partial class AppJsonSerializerContext : JsonSerializerContext;go deeper
Recall that Native AOT needs a JsonSerializerContext with a JsonSerializable attribute for every type an endpoint reads or writes.
Explain the resolver chain: resolvers are asked in order, Insert(0) puts the generated context first, and assigning TypeInfoResolver replaces the chain.
Explain why a forgotten type passes JIT-hosted tests yet fails natively, and build tests against the published binary that hit every response branch.
Decide how contexts are organised across shared contract libraries so that services stay AOT-safe as teams add types.
## The problem source generation solves System.Text.Json normally learns a type's shape **by reflection** the first time it sees it. Native AOT allows neither unbounded reflection (the app is trimmed) nor run-time code generation. Since .NET 8, a trimmed publish (and Native AOT always trims) also turns reflection-based serialization **off by default**, through the `JsonSerializerIsReflectionEnabledByDefault` switch. ASP.NET Core follows that switch. In the 10.0 source, `Microsoft.AspNetCore.Http.Json.JsonOptions` creates its default serializer options with web defaults and sets the resolver to `DefaultJsonTypeInfoResolver` **only when** `JsonSerializer.IsReflectionEnabledByDefault` is true; otherwise it uses an empty combined resolver. In a Native AOT app, therefore, the framework knows **no** types until you tell it. ## The source-generated context You describe your types at compile time: ```csharp [JsonSerializable(typeof(ResizeRequest))] [JsonSerializable(typeof(ResizeResult))] [JsonSerializable(typeof(ResizeResult[]))] internal partial class AppJsonSerializerContext : JsonSerializerContext { } ``` The System.Text.Json source generator fills in the partial class with metadata for each listed type and the types they reference. The class gets a static `Default` instance. ## Registering it in the chain `JsonSerializerOptions.TypeInfoResolverChain` is an ordered list of `IJsonTypeInfoResolver`s. When the serializer needs metadata for a type, it asks each resolver **in order**, and the first one that returns metadata wins. The `webapiaot` template registers the context like this: ```csharp builder.Services.ConfigureHttpJsonOptions(options => { options.SerializerOptions.TypeInfoResolverChain.Insert(0, AppJsonSerializerContext.Default); }); ``` Why **`Insert(0, ...)`** rather than replacing the resolver? - **Order.** At index 0 your context answers first, ahead of any resolver already in the chain, such as the reflection-based fallback wherever reflection is enabled. The metadata your JIT-hosted tests see is then the metadata the native app uses, for every type the context lists. - **Composition.** Other components insert their own contexts; for example, the ProblemDetails setup inserts a `ProblemDetailsJsonContext` into the same chain. Assigning `TypeInfoResolver` instead replaces the whole chain and can drop those. - **Not `AddContext`.** `JsonSerializerOptions.AddContext<T>()` is obsolete (`SYSLIB0049`); its message points to `TypeInfoResolver` or `TypeInfoResolverChain`. Which `JsonOptions` matters too: Minimal APIs read `Microsoft.AspNetCore.Http.Json.JsonOptions`, configured with `ConfigureHttpJsonOptions`. MVC's `AddJsonOptions` configures a different options type, and MVC is not supported under AOT anyway. ## What a forgotten type does Suppose the image-resize endpoint gains a `ResizeError` response and nobody adds `[JsonSerializable(typeof(ResizeError))]`. - **Native AOT executable:** no resolver in the chain can describe `ResizeError`, so serializing it throws when that branch runs, typically surfacing as an unhandled exception and a 500. - **Integration tests on the JIT:** they run in the test project's process, which sets neither `PublishAot` nor `PublishTrimmed`, so reflection stays enabled, the chain still holds the reflection fallback behind your context, and the response serializes. That is why the bug can survive the whole test suite. - **Anonymous types** (`return new { width, height };`) can never be listed in `[JsonSerializable]`, because they have no name to write in `typeof`. The Request Delegate Generator reports `RDG004` for an anonymous return type; replace it with a named record. ## Where else JSON appears in the same app The chain configured through `ConfigureHttpJsonOptions` covers request bodies Minimal APIs bind, results they write and the `HttpRequest`/`HttpResponse` JSON helpers that read those options. It does not automatically cover code that calls `JsonSerializer` directly with its own options object. Pass the generated metadata explicitly there too, for example `JsonSerializer.Serialize(result, AppJsonSerializerContext.Default.ResizeResult)`, which uses the `JsonTypeInfo<ResizeResult>` property the source generator adds to the context. The same goes for `HttpClient` calls that read JSON from another service: the reflection-based `ReadFromJsonAsync<T>()` overloads carry `RequiresUnreferencedCode` and `RequiresDynamicCode`, so the analyzer flags them until you pass a `JsonTypeInfo<T>` or a context. ## Practical rules 1. List every **root** type an endpoint reads or writes, including the exact collection shape you return (`ResizeResult[]` and `List<ResizeResult>` are different roots). 2. Return named records, not anonymous objects. 3. Keep one context per assembly, or insert several contexts, but never assign `TypeInfoResolver` over the chain. 4. Publish with zero warnings and run an integration test against the native executable that hits **every** response branch, including errors. 5. Use `[JsonSourceGenerationOptions]` on the context when the generated code needs its own settings.
- Why can a missing type pass the integration tests but fail in production?Integration tests run in the test project's process on the JIT, and that project sets neither `PublishAot` nor `PublishTrimmed`, so reflection-based serialization stays enabled and ASP.NET Core's JsonOptions keep the reflection-based `DefaultJsonTypeInfoResolver` behind your context. A trimmed or Native AOT publish disables reflection by default, leaving only your context, so the same type throws there. Testing the published executable closes that gap.
- What is wrong with options.SerializerOptions.TypeInfoResolver = AppJsonSerializerContext.Default?Assigning `TypeInfoResolver` replaces the whole chain with that one resolver. Anything other components inserted, such as the ProblemDetails context, is dropped, so their types lose metadata. `TypeInfoResolverChain.Insert(0, ...)` adds your context first while keeping the rest.
- Under Native AOT, System.Text.Json falls back to reflection for types missing from the context.
- AddJsonOptions on the MVC builder configures Minimal API serialization.
- JsonSerializerOptions.AddContext is the current way to register a source-generated context.
- Returning an anonymous object from a Native AOT endpoint is fine because its type exists at compile time.
- Listing ResizeResult in the context also covers List<ResizeResult> as a root type.
Assumes ASP.NET Core 10 on .NET 10; since .NET 8 a trimmed or Native AOT publish disables reflection-based System.Text.Json by default, so the context is mandatory.