skip to content

Native AOT & Trimming

PublishAot compiles a Minimal API app ahead of time for fast startup and low memory, provided it avoids runtime reflection. Interviewers ask what breaks: MVC, Session and reflection-based JSON.

part ofASP.NET Coreread it →
on this pageshow

explore

questions

5

In ASP.NET Core 10, what is Native AOT publishing, and what do you gain and give up compared with a normal JIT-compiled app?

level: juniorimportance: must knowfreq 48%

answer

  1. machine code produced at publish time
  2. <PublishAot>true</PublishAot> in the csproj
  3. start-up time, memory, image size
  4. one runtime identifier, no cross-OS publish
  5. Minimal APIs yes, MVC no

basics

~20 s

Native AOT, switched on with PublishAot in the project file, compiles the app into one native executable at publish time. It starts faster, uses less memory and needs no installed runtime, but loses runtime reflection and code generation, MVC and cross-OS publishing.

solid answer

~50 s

Native AOT is a publish mode: with `<PublishAot>true</PublishAot>` in the `.csproj`, `dotnet publish` compiles the app, the libraries it uses and a stripped-down runtime into **one native executable** for a single runtime identifier, so there is no JIT at start-up and no .NET runtime to install. The gains are **faster start-up, a smaller working set and a smaller deployment** than an untrimmed app, which suits scale-to-zero containers and cold-start-sensitive endpoints. The costs: the app is always trimmed, so **unbounded reflection, `Reflection.Emit` and dynamic assembly loading** do not work; **MVC controllers, Razor Pages, Session, Blazor Server and OData are not supported**, leaving Minimal APIs (plus gRPC and worker services); JSON must use source-generated metadata; publish is slower, needs a native toolchain and cannot cross operating systems. `dotnet run` still uses the JIT, so you test the published binary.

code

xml · 9 lines
xml
<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <InvariantGlobalization>true</InvariantGlobalization>
    <PublishAot>true</PublishAot>
  </PropertyGroup>
</Project>

go deeper

for a junior

Recall the switch, PublishAot in the csproj, and the three wins: start-up time, memory and size. Know that it means Minimal APIs, not MVC controllers.

for a middle

Explain that publish compiles to one native executable per runtime identifier, always trims, and that dotnet run still uses the JIT, so you test the published output.

for a senior

Decide when the trade is worth it: scale-to-zero and dense hosting yes, a large controller or reflection-heavy API no. Insist on zero AOT warnings and a test of the published binary.

for a principal

Weigh AOT as a portfolio choice: which services earn its constraints, what it does to library selection, build agents and toolchains, and how to keep a JIT fallback path.

## What Native AOT is **Native ahead-of-time (AOT) compilation** turns a .NET app into machine code when you publish it, instead of shipping IL that the **just-in-time (JIT) compiler** translates while the process runs. The output is a **single native executable** that contains your code, the parts of the libraries it actually reaches, and a stripped-down runtime. Nothing has to be installed on the target machine, and no method has to be compiled before it can serve its first request. In ASP.NET Core 10 you switch it on with one MSBuild property: ```xml <PropertyGroup> <PublishAot>true</PublishAot> </PropertyGroup> ``` The property belongs in the project file rather than on the command line, because it changes more than publish: it turns on the trim and AOT analyzers during every build and enables the source generators that replace reflection. The `webapiaot` template ("ASP.NET Core Web API (native AOT)") creates a project with `PublishAot` and `InvariantGlobalization` already set and a `Program.cs` built on `WebApplication.CreateSlimBuilder`. ## What you gain The ASP.NET Core documentation lists three benefits, measured against the same app published as a trimmed or untrimmed JIT app: | Benefit | Why it happens | Where it pays | |---|---|---| | **Reduced start-up time** | No JIT work before the first request; code is already native | Scale-to-zero, autoscaling, rolling deployments | | **Reduced memory demand** | No JIT, less runtime machinery in memory | Higher deployment density | | **Smaller disk footprint** | Trimming drops unreachable code | Smaller container images, faster pulls | Picture a **cold-start-sensitive image-resize API**: a container that scales from zero when an upload arrives and must answer quickly. Start-up time is most of that budget, so it is the textbook Native AOT candidate. AOT is a start-up, memory and size optimisation. It is not a promise of more requests per second under steady load, so measure throughput before and after rather than assuming it. ## What you give up - **Run-time code generation and dynamic loading.** The .NET docs list no `System.Reflection.Emit`, no `Assembly.LoadFile`, and `System.Linq.Expressions` running only in interpreted form. - **Unbounded reflection.** Native AOT always trims, so code reached only through reflection may simply not be in the executable. - **Several ASP.NET Core features.** The support table marks **MVC, Blazor Server, Session, OData, SPA and "other authentication"** as not supported; **Minimal APIs and SignalR** as partially supported; and CORS, health checks, JWT bearer authentication, output caching, rate limiting, static files, WebSockets and gRPC as supported. - **Reflection-based JSON.** Request and response types need a source-generated `JsonSerializerContext`. - **Portability of the binary.** You publish for one runtime identifier, and Native AOT does not support cross-OS compilation; a Linux binary runs on the distribution version it was built on or a newer one. - **Build convenience.** Publishing needs the platform's native toolchain (for example clang on Linux or the C++ desktop workload in Visual Studio on Windows) and takes noticeably longer. ## How you know it will work 1. **Read the warnings.** With `PublishAot` set, analyzers report trim warnings (`IL2026`) and AOT warnings (`IL3050`) during build, and publish analyses the whole app again, NuGet packages included. The docs' rule: if publish produces no AOT warnings, the app can be expected to behave like its JIT-compiled version. 2. **Test the published executable.** `dotnet run` still uses the JIT even when `PublishAot` is set, so a run under the debugger proves nothing about trimming. 3. **Publish early and often**, so a new package that is not AOT-compatible shows up in the week it was added. ## Native AOT versus its neighbours - **ReadyToRun** (`PublishReadyToRun`) pre-compiles IL but keeps the JIT and full reflection; start-up improves less, compatibility is untouched. - **Trimming alone** (`PublishTrimmed`) shrinks a self-contained app but still JIT-compiles it. - **Native AOT** implies trimming and removes the JIT, which is why it gains the most and restricts the most. Choose it for small Minimal API services where start-up and density dominate. Keep the JIT for a large controller-based API, a Razor Pages site, or anything built on reflection-heavy libraries.

  • Does `dotnet run` exercise the Native AOT build when PublishAot is set?
    No. `PublishAot` only changes what `dotnet publish` produces; `dotnet run` and the debugger still run IL on the JIT. What you do get at build time are the trim and AOT analyzers and the source generators. So the only real proof is running the published native executable, ideally in the same container image you deploy.
  • How does Native AOT differ from ReadyToRun?
    ReadyToRun (`PublishReadyToRun`) adds pre-compiled native code to ordinary IL assemblies, so start-up improves, but the JIT, full reflection and dynamic loading all remain. Native AOT removes the JIT, always trims and produces one executable, so it gains more start-up time and memory but restricts which APIs and ASP.NET Core features you may use.

Native AOT is like furniture assembled at the factory: it arrives ready to use with no assembly on site, but you can no longer fit parts the factory did not know about when it built the piece.

  • Native AOT makes every ASP.NET Core app faster, including MVC controller APIs.
  • Setting PublishReadyToRun is the switch that produces a Native AOT executable.
  • dotnet run on a PublishAot project already tests the native executable.
  • A Native AOT binary published on Windows can be copied into a Linux container.
  • Native AOT keeps the JIT around as a fallback for reflection-heavy code.
open as a page

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?

level: seniorimportance: must knowfreq 42%

basics

~20 s

MVC 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.

open as a page

In ASP.NET Core 10, what does WebApplication.CreateSlimBuilder leave out compared with CreateBuilder, and how do you restore HTTPS or a regex route constraint?

level: middleimportance: should knowfreq 30%

basics

~10 s

CreateSlimBuilder keeps configuration, user secrets and console logging but drops Kestrel HTTPS and HTTP/3, IIS integration, extra logging providers, hosting startup and the regex route constraint. UseKestrelHttpsConfiguration restores HTTPS; AddRouting or SetParameterPolicy restores regex.

open as a page

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?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Native 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.

open as a page

In ASP.NET Core 10 Minimal APIs, what does the Request Delegate Generator do, when is it switched on, and why might it skip an endpoint?

level: seniorimportance: nice to knowfreq 18%

basics

~20 s

The Request Delegate Generator is a source generator that writes each Minimal API endpoint's request delegate at compile time instead of building it by reflection at start-up. PublishAot or PublishTrimmed turns it on; it skips endpoints it cannot analyse statically and reports RDG diagnostics.

open as a page