SharpRuneOpen playground

Native AOT for ASP.NET Core on .NET 10: a practical readiness guide

What PublishAot changes for an ASP.NET Core service on .NET 10, how to clear trim and AOT warnings, what is still unsupported, and how to measure whether the trade is worth it.

Conceptual illustration of managed code being compiled ahead of time into a single native executable that is ready to deploy.

Ahead-of-time compilation turns managed code into a single native executable before deployment. The illustration is conceptual. · ImageGen illustration

What PublishAot actually changes

Native ahead-of-time compilation changes when your code becomes machine code. With PublishAot set, dotnet publish compiles the application’s IL, the framework code it reaches and its package dependencies into native code for one runtime identifier, such as linux-x64. The result is a self-contained executable, carrying a stripped-down runtime inside it, that needs neither an installed .NET runtime nor a JIT compiler. By default the native symbols go to a separate file: .dbg on Linux, .pdb on Windows and a .dSYM folder on macOS.

Constraints follow from that model. Trimming is mandatory. Runtime code generation, such as System.Reflection.Emit, and dynamic loading, such as Assembly.LoadFile, are unavailable. The binary targets one operating system and architecture. Development is unchanged: dotnet run, dotnet test and the debugger still use the JIT, while PublishAot enables compatibility analysis during build and editing and repeats it over the whole application, packages included, at publish time.

This guide targets net10.0, the current long-term support release, supported until November 2028. .NET 11 shipped in November 2026 as a standard-term release. Compatibility tables change between versions, so check the documentation for the release you deploy.

References: Microsoft: Native AOT deployment overview · Microsoft: ASP.NET Core support for Native AOT

Startup, memory and the throughput you trade

Microsoft’s ASP.NET Core documentation lists three benefits: a smaller disk footprint, faster startup and lower memory demand, the last depending on the work the app does. Its benchmark chart compares Native AOT builds of the template apps with trimmed and untrimmed JIT builds and shows the AOT build lower on all three. The deployment documentation adds that the benefit is most significant where many instances are deployed. Compare that with your own situation: many replicas, frequent scale-out, scale-to-zero or dense packing of small services.

The cost sits on the other side of the JIT. Tiered compilation and dynamic profile-guided optimization recompile hot methods using what the running process has observed, and Microsoft’s .NET 8 runtime notes put the average gain from dynamic PGO at about 15 percent across its benchmark suite. A native binary never re-optimizes after deployment, so a long-running service can see lower steady-state throughput than it would on the JIT. The documented limitations add that System.Linq.Expressions always uses its slower interpreted form, and that generic code over value types is pre-generated for every instantiation, which can enlarge the binary considerably.

Setting OptimizationPreference to Size or Speed shifts the compiler’s default blend towards a smaller executable or higher peak throughput, but neither setting restores runtime feedback. Measure throughput in your own load test.

References: Microsoft: ASP.NET Core support for Native AOT · Microsoft: Native AOT deployment overview

Begin with minimal APIs and CreateSlimBuilder

ASP.NET Core supports Native AOT for minimal APIs, gRPC services and worker services. The webapiaot template shows the intended shape: minimal APIs only, CreateSlimBuilder instead of CreateBuilder, HTTP only on the assumption that TLS ends at an ingress, no IIS launch profile, PublishAot in the project file and JSON source generation already wired in. In .NET 10 the template also includes OpenAPI document generation by default, which the --no-openapi option removes.

CreateSlimBuilder keeps appsettings configuration, user secrets, console logging and logging configuration. It omits hosting startup assemblies, UseStartup, the EventLog, Debug and EventSource logging providers, static web assets, IIS integration, HTTPS endpoints, QUIC, and the regex and alpha route constraints; UseKestrelHttpsConfiguration and UseQuic restore HTTPS and HTTP/3. CreateEmptyBuilder omits even the defaults the slim builder keeps. A service that relies on an omitted piece can compile and still fail at run time, so inventory what the current host uses before switching.

The complete Program.cs below registers every body type with a source-generated context and uses only middleware listed as supported.

.NET 10 SDK · ASP.NET Core

C#
using System.Text.Json.Serialization;

var builder = WebApplication.CreateSlimBuilder(args);

builder.Services.ConfigureHttpJsonOptions(options =>
{
    options.SerializerOptions.TypeInfoResolverChain.Insert(0, AppJsonContext.Default);
});
builder.Services.AddHealthChecks();

var app = builder.Build();

var orders = app.MapGroup("/orders");

orders.MapGet("/{id:int}", (int id) =>
    id > 0
        ? Results.Ok(new OrderResponse(id, "Pending", DateTimeOffset.UtcNow))
        : Results.NotFound());

orders.MapPost("/", (CreateOrderRequest request) =>
{
    var created = new OrderResponse(Random.Shared.Next(1, int.MaxValue), "Created", DateTimeOffset.UtcNow);
    return TypedResults.Created($"/orders/{created.Id}", created);
});

app.MapHealthChecks("/health");

app.Run();

public sealed record CreateOrderRequest(int CustomerId, string Sku, int Quantity);

public sealed record OrderResponse(int Id, string Status, DateTimeOffset CreatedAt);

// Every type that crosses the HTTP body is listed here; metadata is generated at build time.
[JsonSerializable(typeof(CreateOrderRequest))]
[JsonSerializable(typeof(OrderResponse))]
internal partial class AppJsonContext : JsonSerializerContext
{
}

References: Microsoft: ASP.NET Core support for Native AOT

Why reflection-based JSON fails, and what the context fixes

By default, System.Text.Json discovers properties and constructors through reflection at run time. Trimming can remove members that nothing references statically, and Native AOT does not support every reflection API the serializer needs. Because development and tests run on CoreCLR, where reflection works, the failures are hard to predict. Reflection-based serialization is disabled automatically in trimmed apps; setting JsonSerializerIsReflectionEnabledByDefault to false explicitly, as the documentation recommends, makes reflection-dependent code throw a descriptive InvalidOperationException on CoreCLR too, so ordinary tests fail in the same place.

The fix is a partial class deriving from JsonSerializerContext, annotated with JsonSerializable for each root type. Member types are discovered from the roots, except that a collection serialized as a root needs its own entry and a member declared as object needs every runtime type it may hold registered. For enums written as strings, use the generic JsonStringEnumConverter or the UseStringEnumConverter option; the non-generic converter is not supported by the Native AOT runtime.

ASP.NET Core finds the metadata through TypeInfoResolverChain, queried in order with the first non-null result winning, which is why the template inserts its context at position zero. Several contexts can be chained or combined with JsonTypeInfoResolver.Combine. Elsewhere, call serializer overloads that take a JsonTypeInfo, such as AppJsonContext.Default.OrderResponse; the overloads taking only a generic type and options are annotated as unsafe for trimming and AOT.

References: Microsoft: Source generation in System.Text.Json · Microsoft: ASP.NET Core support for Native AOT

Let the Request Delegate Generator bind at build time

Without Native AOT, minimal APIs compile each Map call into a request delegate in memory when the app starts, generating the code that binds route values, query strings and bodies to handler parameters. A native binary cannot rely on that. The Request Delegate Generator is a source generator that turns each MapGet, MapPost and related call into a RequestDelegate at build time, compiled into the native image. It also roots the types your endpoints use, so the code they need is not trimmed away.

The generator switches on automatically when Native AOT publishing or trimming is enabled. Setting EnableRequestDelegateGenerator to true enables it in an ordinary JIT project, which the documentation suggests both for evaluating compatibility and for reducing startup work. For an existing minimal API that is an inexpensive first step.

Unsupported handlers produce RDG diagnostics as warnings that do not stop the build: RDG002 when the handler cannot be resolved, RDG004 for anonymous types, RDG005 for abstract types, and others for AsParameters misuse and unusable constructors. Treat them as failures. Parameters not bound from the body need no JSON metadata at all; a query-string parameter can be any type that implements IParsable.

References: Microsoft: Request Delegate Generator for Native AOT

Read trim and AOT warnings as a contract

RequiresUnreferencedCode marks code that is fundamentally incompatible with trimming, such as loading a type by a name supplied at run time; callers receive IL2026. DynamicallyAccessedMembers expresses a requirement instead: a Type that flows into reflection must keep, for example, its public methods, and values that do not satisfy the requirement raise warnings such as IL2070. RequiresDynamicCode, reported to callers as IL3050, marks code that may need native code that cannot exist ahead of time, typically MakeGenericType over arbitrary types or reflection emit.

Microsoft’s guidance sets a sensible order. Remove the reflection, usually with generics or a source generator. If the types are known at compile time, annotate with DynamicallyAccessedMembers and propagate the annotation back to where the type originates, using the narrowest member types, since All keeps every member. If the code is genuinely dynamic, mark it with the matching Requires attribute so the warning moves to callers with a message that explains the alternative. Suppress only when safety is established, and only with UnconditionalSuppressMessage: SuppressMessage and pragma directives exist only in source, so the trimmer and AOT compiler never see them.

RuntimeFeature.IsDynamicCodeSupported lets code choose an AOT-safe path at run time, and setting DynamicCodeSupport to false in a test configuration exercises that path under the JIT without a native publish.

.NET 10 SDK · ASP.NET Core

C#
using System.Diagnostics.CodeAnalysis;

public static class HandlerCatalog
{
    // Trim-compatible: the annotation tells the compiler to keep the public methods
    // of any type that flows into this parameter, so callers passing typeof(X) are safe.
    public static IEnumerable<string> PublicMethodNames(
        [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type type)
        => type.GetMethods().Select(method => method.Name);

    // Not analyzable: the type name arrives at run time and the generic type is closed
    // at run time. Callers receive IL2026 and IL3050 with these messages.
    [RequiresUnreferencedCode("Loads handler types by name. Register handlers explicitly instead.")]
    [RequiresDynamicCode("Closes a generic handler type at run time. Register handlers explicitly instead.")]
    public static object? CreateHandler(string typeName, Type messageType)
    {
        var openType = Type.GetType(typeName, throwOnError: true)!;
        var closedType = openType.MakeGenericType(messageType);
        return Activator.CreateInstance(closedType);
    }
}

References: Microsoft: Fixing trim warnings · Microsoft: Introduction to AOT warnings

Make the build fail before production does

Warnings protect you only if they block something. The trimming documentation states that NoWarn, WarningsAsErrors, WarningsNotAsErrors and TreatWarningsAsErrors are respected by the toolchain, with ILLinkTreatWarningsAsErrors available to keep trim warnings advisory. For a native service, prefer strictness. Microsoft’s ASP.NET Core guidance is direct: an app that issues AOT warnings during publishing might not work correctly, while one that publishes without them can be expected to work the same as its JIT build.

By default, trim analysis reports at most one warning for each assembly that comes from a package reference, which hides how much work a dependency needs; setting TrimmerSingleWarn to false shows every warning. Expect the first strict publish to fail and treat its output as the readiness backlog. Keep PublishAot in the project file rather than on the command line, since it controls behavior outside publish, and publish in CI on every change, because publish-time analysis covers code the build-time analyzers do not.

Libraries make the opposite declaration. IsAotCompatible turns on IsTrimmable and the trim, single-file and AOT analyzers. Target net8.0 or later, the minimum for AOT analysis warnings, and condition the property with IsTargetFrameworkCompatible when the library also targets netstandard2.0. Since .NET 10 the property is recorded as assembly metadata, and the opt-in VerifyReferenceAotCompatibility property reports references that lack it as IL3058.

.NET 10 SDK · ASP.NET Core

Orders.Api.csproj
<!-- Orders.Api.csproj -->
<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>

    <!-- Native AOT on publish; trim and AOT analyzers during build and editing. -->
    <PublishAot>true</PublishAot>
    <InvariantGlobalization>true</InvariantGlobalization>

    <!-- Reflection-based JSON fails the same way under the JIT, so tests catch it. -->
    <JsonSerializerIsReflectionEnabledByDefault>false</JsonSerializerIsReflectionEnabledByDefault>

    <!-- Analyzer findings break the build; package warnings are shown individually. -->
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
    <TrimmerSingleWarn>false</TrimmerSingleWarn>
  </PropertyGroup>

</Project>

References: Microsoft: Native AOT deployment overview · Microsoft: ASP.NET Core support for Native AOT · Microsoft: Fixing trim warnings

Configuration, options and logging have generators too

The reflection-based configuration binder walks options types at run time. Since .NET 8 a configuration binding source generator intercepts Bind, Get and Configure call sites using C# interceptors and substitutes generated code. The .NET 8 release notes state that it is enabled by default in AOT-compiled web apps and when PublishTrimmed is set; elsewhere you opt in with EnableConfigurationBindingGenerator. With PublishAot on and the generator disabled, binding calls raise IL2026 and IL3050, a useful sign that something has switched it off.

The options validation generator replaces reflective data annotation checks. Apply OptionsValidator to an empty partial class that implements IValidateOptions for your options type, register it as a singleton, and the Validate method is written at compile time, with reflection-free substitutes for the Range, MinLength, MaxLength and Length attributes. It is enabled by default in ASP.NET Core projects. ValidateOnStart then makes a missing or invalid setting stop the host at startup rather than fail the first request that needs it.

Ordinary ILogger calls work under Native AOT, but the LoggerMessage generator fits the same build-time approach: annotated partial methods receive generated implementations that avoid boxing, temporary allocations and copies as far as possible, and misuse is reported at compile time.

.NET 10 SDK · ASP.NET Core

C#
using System.ComponentModel.DataAnnotations;
using Microsoft.Extensions.Options;

public sealed class PaymentGatewayOptions
{
    public const string SectionName = "PaymentGateway";

    [Required]
    public string BaseUrl { get; set; } = "";

    [Range(1, 60)]
    public int TimeoutSeconds { get; set; } = 10;
}

// The options validation generator writes Validate at compile time.
[OptionsValidator]
public partial class PaymentGatewayOptionsValidator : IValidateOptions<PaymentGatewayOptions>
{
}

public static partial class PaymentLog
{
    [LoggerMessage(EventId = 2001, Level = LogLevel.Warning,
        Message = "Payment gateway call timed out after {TimeoutSeconds} seconds")]
    public static partial void GatewayTimedOut(ILogger logger, int timeoutSeconds);
}

public static class PaymentGatewayRegistration
{
    public static IServiceCollection AddPaymentGateway(
        this IServiceCollection services, IConfiguration configuration)
    {
        // In an AOT web project, the binding generator intercepts this Bind call.
        services.AddOptions<PaymentGatewayOptions>()
            .Bind(configuration.GetSection(PaymentGatewayOptions.SectionName))
            .ValidateOnStart();

        services.AddSingleton<IValidateOptions<PaymentGatewayOptions>, PaymentGatewayOptionsValidator>();
        return services;
    }
}

References: Microsoft: Compile-time configuration source generation

What is not supported, or only partly

The ASP.NET Core compatibility table lists MVC, Blazor Server, Session, SPA, OData and authentication other than JWT as not supported, which rules out controllers, Razor Pages and server-side Blazor. Minimal APIs are partially supported, subject to the JSON and binding constraints above. gRPC, health checks, CORS, output and response caching, rate limiting, compression, URL rewriting, static files, WebSockets and JWT authentication are among the features listed as supported. Blazor WebAssembly has its own, separate ahead-of-time compilation to WebAssembly.

SignalR became partially supported in .NET 9, for client and server, and that release’s notes list specific limits: only the JSON hub protocol, using source generation configured through JsonHubProtocolOptions; no IAsyncEnumerable or ChannelReader hub parameters over value types; no strongly typed hubs under PublishAot, where they produce warnings and a runtime exception; and only Task, ValueTask and their generic forms as asynchronous return types.

The platform limits reach every dependency: no dynamic assembly loading, so no plugin directories; no runtime code generation, which excludes proxy generators built on reflection emit; no C++/CLI; and no built-in COM on Windows. The documentation names the patterns that break libraries: discovering types through reflection, loading libraries conditionally and generating code on the fly. The trimming guidance also warns that complex dependency injection containers are often incompatible. Look for an explicit statement of Native AOT support from each dependency, then let the strict publish confirm it.

References: Microsoft: ASP.NET Core support for Native AOT · Microsoft: Native AOT deployment overview · Microsoft: Fixing trim warnings

EF Core 10: treat Native AOT as an experiment

Entity Framework Core is the dependency most likely to decide the question. Its documentation calls NativeAOT support and query precompilation highly experimental and not yet suited for production use, and recommends against deploying EF NativeAOT applications in production. Neither the EF Core 10 release notes nor, at the time of writing, the EF Core 11 notes change that status. EF Core 10 itself is a long-term support release supported until November 10, 2028; the caution concerns one feature, not the product.

Precompilation statically identifies EF LINQ queries and generates C# interceptors containing each query’s SQL and materialization code. It needs an InterceptorsNamespaces opt-in for Microsoft.EntityFrameworkCore.GeneratedInterceptors and the Microsoft.EntityFrameworkCore.Tasks package, which does the work during publish; dotnet ef dbcontext optimize with the --precompile-queries and --nativeaot options produces the same output for inspection. Any source change invalidates the interceptors, so this belongs in CI, and publishing still reports trim and AOT warnings.

Queries composed across statements, such as a Where added only when a filter is present, cannot be precompiled, though they can sometimes be rewritten as separate complete queries. LINQ query syntax and value converters with captured state are unsupported, generated code can be large, and providers may need to add support. For production today, keep EF Core out of native binaries, or stay on the JIT and use --precompile-queries alone, which the documentation offers for startup gains without NativeAOT.

References: Microsoft: EF Core NativeAOT support and precompiled queries (experimental)

Container images: small to run, large to build

A native executable needs only the native dependencies of a self-contained app, so runtime-deps images are the natural base; Microsoft describes them as convenient for self-contained and native AOT scenarios, with a standard user and port definitions included. Since .NET 8, Microsoft’s .NET images default ASP.NET Core to port 8080, which a non-root user can bind. Ubuntu chiseled variants are smaller again: without ICU or tzdata they suit InvariantGlobalization builds, and extra variants exist for apps that need culture or time zone data. With no shell or package manager inside, use exec-form entry points and the orchestrator’s HTTP probes rather than curl in the container.

The build stage is the opposite: SDK images with an -aot suffix include the native toolchain and, according to Microsoft’s documentation, are commonly twice the size of regular SDK images. Tag conventions have shifted between releases, so confirm the current tags in Microsoft’s registry and pin releases by digest.

In the Dockerfile below, the runtime identifier must match the architecture of the images the build pulls, and the symbol file is moved aside, out of the runtime image but available to archive for native debugging and crash dumps. Alternatively, SDK container publishing infers a runtime-deps base for self-contained projects and lets ContainerFamily choose a variant, provided you build on a Linux agent of the target architecture.

.NET 10 SDK · ASP.NET Core

Dockerfile
# Dockerfile: run this build on an x64 agent, or change the RID and the agent to Arm64 together.
FROM mcr.microsoft.com/dotnet/sdk:10.0-noble-aot AS build
WORKDIR /src
COPY . .
RUN dotnet publish Orders.Api.csproj -c Release -r linux-x64 -o /app \
    && mkdir -p /symbols && mv /app/*.dbg /symbols/

FROM mcr.microsoft.com/dotnet/runtime-deps:10.0-noble-chiseled
WORKDIR /app
COPY --from=build /app .
ENTRYPOINT ["./Orders.Api"]

References: Microsoft: .NET container images · Microsoft: Native AOT deployment overview

Cross-compilation: build where the binary will run

Native AOT links compiled code with platform libraries using the platform’s own linker. Because there is no standard way to obtain one operating system’s SDK on another, Native AOT does not support cross-OS compilation; building for Linux from Windows or macOS needs emulation, such as a virtual machine or WSL. The prerequisites differ accordingly: the Desktop development with C++ workload on Windows, clang on Linux with build-base added on Alpine, and the Xcode command line tools on macOS.

Cross-architecture builds between x64 and Arm64 work with the right toolchain: the matching Visual Studio C++ build tools on Windows, the default Xcode install on macOS, and on Linux a cross-linker such as clang, a target-compatible objcopy or strip, and the target’s C runtime and zlib object files. Microsoft’s sample commands for Ubuntu are explicitly not guaranteed, and a native build runner per architecture is usually simpler.

Linux adds a version boundary: a binary built on Ubuntu 20.04 runs on 20.04 and later, but not on 18.04. Build on the distribution and version of the runtime image, as the Dockerfile does with Ubuntu 24.04 in both stages, or on the oldest version you support. ReadyToRun, by contrast, supports many cross-platform and cross-architecture targets.

References: Microsoft: Native AOT cross-compilation · Microsoft: Native AOT deployment overview

Measure before and after on equal terms

Decide what you want to improve, then measure three builds of the same commit: framework-dependent on the JIT, ReadyToRun or trimmed self-contained, and Native AOT. That mirrors Microsoft’s chart and separates precompilation from removing the JIT. Give every build identical CPU and memory limits and the same garbage collector configuration, and record those settings with the results.

Four measurements usually decide the case: image size, compressed and uncompressed; time from container start to the first successful response, measured outside the process, since a startup log line is not a served request; working set or container memory after a fixed warm-up, as the orchestrator reports it; and steady-state throughput and latency percentiles after the JIT build has tiered up, because a cold JIT process flatters AOT. Repeat each run and report medians and tails, not a single best result.

Check the diagnostic story too. With EventSourceSupport set to true, dotnet-counters, dotnet-trace and dotnet-monitor work through EventPipe, and CPU profiling with tools such as perf is partially supported. The managed debugger cannot attach to the native binary, although native debuggers can, using the symbol file. Managed heap analysis is not currently supported, so dotnet-gcdump will not help with a production memory leak.

.NET 10 SDK · ASP.NET Core

measure.sh
# measure.sh: run on a Linux host with GNU date; repeat for every build of the same commit.
IMAGE=orders-api:aot

docker image inspect "$IMAGE" --format 'local image size in bytes: {{.Size}}'

start=$(date +%s%N)
docker run -d --rm --name orders-test --cpus 1 --memory 256m -p 8080:8080 "$IMAGE" >/dev/null
until curl -fs http://localhost:8080/health >/dev/null; do sleep 0.01; done
echo "first healthy response after $(( ($(date +%s%N) - start) / 1000000 )) ms"

# Apply the same warm-up load to every build at this point, then read memory.
docker stats --no-stream --format '{{.Name}} {{.MemUsage}}' orders-test
docker stop orders-test >/dev/null

References: Microsoft: ASP.NET Core support for Native AOT · Microsoft: Native AOT deployment overview

A decision checklist, including when to stay on the JIT

Native AOT is a deployment choice, not a quality badge. Stay on the JIT when the service needs MVC, Razor Pages, Blazor Server or an unsupported authentication handler; when EF Core must run inside the native binary in production; when a dependency loads plugins, emits code or relies on unannotated reflection; when you cannot build on the target platform in CI; when a few long-lived instances gain little from faster startup and may lose throughput; or when incident response depends on managed heap dumps.

Middle paths remain, all usable without Native AOT: ReadyToRun for startup, trimming for size, CreateSlimBuilder for a leaner host, the Request Delegate Generator for pregenerated endpoints and precompiled EF queries.

If the service passes, move in order. Confine the host to supported features and switch to CreateSlimBuilder. Register body types in a source-generated context, disable reflection-based JSON and run the existing tests. Enable the Request Delegate Generator and clear its diagnostics. Turn on PublishAot with warnings as errors and TrimmerSingleWarn disabled, then publish in CI on the target platform until the list is empty, fixing code before annotating it and annotating before suppressing. Move binding, validation and logging onto generators, and isolate dependencies without a Native AOT story.

Finally, build the image on the matching architecture, archive the symbols and measure against the target you set. Keep the JIT build in the pipeline until the native one has come through a real incident and a routine dependency upgrade. If the numbers do not justify the constraints, the leaner host and generated serializers still serve the JIT build.

References: Microsoft: ASP.NET Core support for Native AOT · Microsoft: Native AOT deployment overview · Microsoft: EF Core NativeAOT support and precompiled queries (experimental)

Continue with SharpRune

Sources & further reading

Technical references checked against primary documentation. Code samples in this article target .NET 10 SDK · ASP.NET Core; in the browser playground, choose .NET 10 or 11 in Settings.

Illustration created with ImageGen for SharpRune. Article and examples are educational; validate behavior in your target runtime.
Put an idea into practice