Your team sets PublishAot on an existing ASP.NET Core 10 API built with controllers and Session; what breaks, and how do IL2026 and IL3050 warnings flag it first?
answer
- RequiresUnreferencedCode on AddControllers
- IL2026: trimming may remove what it needs
- IL3050: needs run-time code generation
- analyzers at build, full-app scan at publish
- zero warnings or no ship
basics
~20 sMVC controllers and Session are not supported under Native AOT: AddControllers and AddSession carry RequiresUnreferencedCode, so the build reports IL2026, and calls marked RequiresDynamicCode report IL3050. Publish rescans every package; any warning means the native app may fail at run time.
solid answer
~50 sUnder Native AOT the app is always trimmed and cannot generate code at run time, so ASP.NET Core features built on reflection stop being safe. `AddControllers`, `AddMvc` and `AddRazorPages` are annotated `[RequiresUnreferencedCode("MVC does not currently support trimming or native AOT.")]` (Razor Pages has its own message), and `AddSession` carries the same kind of message, so the trim analyzer reports **IL2026** at each call. **IL3050** is the AOT analyzer's warning for members marked `[RequiresDynamicCode]`, such as the reflection-based JSON helpers or `MakeGenericType` on an unknown type. With `PublishAot` set, both analyzers run on every build, and `dotnet publish` analyses the whole app again, NuGet packages included. A warning means the published executable may fail at run time even though `dotnet run` works. The fix is a migration: move endpoints to Minimal APIs, move session state elsewhere, use source-generated JSON, and ship only when publish is warning-free.
code
csharp · 14 linesvar builder = WebApplication.CreateBuilder(args);
// IL2026: 'AddControllers' has RequiresUnreferencedCodeAttribute:
// "MVC does not currently support trimming or native AOT."
builder.Services.AddControllers();
// IL2026: 'AddSession' has RequiresUnreferencedCodeAttribute
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession();
var app = builder.Build();
app.UseSession();
app.MapControllers();
app.Run();go deeper
Know that controllers, Razor Pages and Session are not supported under Native AOT, and that publish warnings must be fixed, not ignored.
Explain IL2026 versus IL3050, which attributes raise them, and that analyzers run at build while publish rescans every package.
Lead the migration: inventory warnings per package, move endpoints to Minimal APIs, replace session state, gate CI on a warning-free publish and test the native binary.
Judge whether a legacy controller API should go AOT at all, or whether new small services should take AOT while the monolith stays on the JIT.
## Why existing code breaks A Native AOT publish does two things a JIT-compiled app never does. It **trims**: whatever static analysis cannot prove is reachable is removed from the executable. And it **cannot generate code at run time**: there is no JIT, so nothing can be emitted or compiled on the fly. ASP.NET Core features that discover controllers, actions, filters, model binders or serialisable types through reflection, or that build delegates at run time, are exactly the ones these two rules break. The official support table for ASP.NET Core sums it up: | Status | Features | |---|---| | **Not supported** | MVC, Blazor Server, Session, OData, SPA, "other authentication" | | **Partial** | Minimal APIs, SignalR | | **Supported** | CORS, gRPC, health checks, HTTP logging, JWT authentication, localization, output and response caching, rate limiting, compression, rewrite, static files, WebSockets | So an API built with `[ApiController]` controllers and `HttpContext.Session` hits two unsupported rows at once. ## How the framework tells you ASP.NET Core does not leave you to discover this in production. Its unsafe entry points are **annotated**: - `AddMvc`, `AddControllers` and `AddControllersWithViews` carry `[RequiresUnreferencedCode("MVC does not currently support trimming or native AOT.")]`; `AddRazorPages` carries the Razor Pages equivalent. - `AddSession` carries `[RequiresUnreferencedCode("Session State middleware does not currently support trimming or native AOT.")]`. - `MapGet`, `MapPost` and friends with a `Delegate` handler carry both `[RequiresUnreferencedCode]` and `[RequiresDynamicCode]`; the Request Delegate Generator suppresses those on the endpoints it can generate. - The reflection-based `ReadFromJsonAsync<T>` and `WriteAsJsonAsync<T>` overloads carry both attributes too. Two warning ids carry these annotations to you: - **IL2026**: you call a member marked `RequiresUnreferencedCodeAttribute`; trimming may remove what it needs. - **IL3050**: you call a member marked `RequiresDynamicCodeAttribute`; it may need code generated at run time, which Native AOT cannot do. ## When the warnings appear Setting `PublishAot` to `true` makes the SDK turn on `EnableTrimAnalyzer`, `EnableAotAnalyzer` and `EnableSingleFileAnalyzer`, so Roslyn analyzers flag your own calls **during every build** and in the editor. At **publish**, the whole app, every NuGet package included, is analysed again; that is where warnings from libraries you do not own surface. The rule of thumb from the docs: an app that publishes with no AOT warnings can be expected to behave like the JIT build; an app with warnings might not. The trap is that the JIT build keeps working. `dotnet run`, unit tests and the debugger all run on the JIT, where reflection is complete, so a team that ignores the warnings finds out when the native executable fails at run time. ## What not to do - Do not silence IL2026 or IL3050 with `#pragma` or `[UnconditionalSuppressMessage]` to get a clean publish. Suppression is for code you have proved safe; on `AddControllers` it just moves the failure to run time. - Do not expect `JsonSerializerIsReflectionEnabledByDefault=true` to rescue MVC: it re-enables reflection-based JSON, but controllers are still unsupported. - Do not treat a passing `dotnet test` run as evidence; it never ran the native code. ## A migration path 1. Publish once with `PublishAot` to get the full warning list, grouped by package. 2. Move controller actions to **Minimal API** endpoints, using `MapGroup` to keep the route structure. 3. Replace `HttpContext.Session` with state the client sends back or a store your endpoints read explicitly. 4. Add a source-generated `JsonSerializerContext` for every body type. 5. Replace or upgrade packages that still warn; library authors declare support with `<IsAotCompatible>true</IsAotCompatible>`, which turns the analyzers on in the library's own build. 6. Gate the pipeline on a warning-free publish and run integration tests against the published executable. ## Reading a warning Each warning names the member you called and repeats the message from its attribute, so the text itself usually tells you why and where to look. A useful triage: | Where the warning points | What it usually means | Typical action | |---|---|---| | Your `Program.cs` (`AddControllers`, `AddSession`) | A framework feature with no AOT support | Redesign around a supported feature | | Your own reflection (`Type.GetType`, `MakeGenericType`) | Code the trimmer cannot follow | Replace with generics or annotate with `DynamicallyAccessedMembers` | | A NuGet package, reported at publish | The library is not annotated or not compatible | Upgrade, replace, or keep the service on the JIT | If steps 2 and 3 are most of the code base, the honest answer may be to keep this service on the JIT and use Native AOT for new, small services instead.
- What is the difference between IL2026 and IL3050?IL2026 comes from the trim analyzer: the called member is marked `RequiresUnreferencedCode`, so code it reaches through reflection may be trimmed away. IL3050 comes from the AOT analyzer: the member is marked `RequiresDynamicCode`, so it may need code generated at run time, which Native AOT cannot do. Many reflection-based ASP.NET Core APIs, such as `MapGet` with a delegate, carry both.
- When is suppressing IL2026 with UnconditionalSuppressMessage acceptable?Only when you have proved the code is safe after trimming, for example because every type it reflects over is kept alive elsewhere or annotated with `DynamicallyAccessedMembers`, and you write that justification in the attribute. Suppressing the warning on `AddControllers` or `AddSession` is never that case, because the framework itself states it does not support trimming there.
- If dotnet run and the unit tests pass, the Native AOT executable will behave the same.
- IL2026 and IL3050 are style warnings that can be suppressed to get a clean publish.
- Setting JsonSerializerIsReflectionEnabledByDefault to true makes MVC controllers work under Native AOT.
- The analyzers only run during dotnet publish, so build output says nothing about AOT safety.
- Session works under Native AOT as long as it is backed by a distributed cache.