12-Factor App with ASP.NET Core (.NET 10): 7 Errors I Hit

Last updated: October 27, 2026 · Tested with .NET 10.0.12 (SDK 10.0.401), EF Core Sqlite 10.0.14, Microsoft.Extensions.Http.Resilience 10.10.0, container base image mcr.microsoft.com/dotnet/aspnet:10.0 (10.0.14), Windows 11

Short answer: a 12-factor ASP.NET Core app reads every deploy-specific value from environment variables (validated with ValidateOnStart), binds to the port the platform gives it, keeps no state in the process (including Data Protection keys), shuts down cleanly on SIGTERM, logs JSON to stdout, and runs migrations as a separate one-off process from the same build. ASP.NET Core on .NET 10 does most of this out of the box. I built one small app that applies all twelve factors and ran each one; below are the real outputs and the seven messages I hit on the way.

You see this Factor What it means
OptionsValidationException: DataAnnotation validation failed for 'StorageOptions' at startup 3 Config An environment variable is missing or invalid; ValidateOnStart stopped the app before it took traffic (this is the good outcome)
export: `Storage:BucketName=x': not a valid identifier 3 Config Shells don’t accept : in variable names; use Storage__BucketName
error NU1004: ... The packages lock file is inconsistent with the project dependencies 2 Dependencies A package version changed without updating packages.lock.json
Overriding HTTP_PORTS '8080' and HTTPS_PORTS ''. Binding to values defined by URLS instead 7 Port binding ASPNETCORE_URLS beats ASPNETCORE_HTTP_PORTS; the app is not on 8080
CryptographicException: The key {...} was not found in the key ring. 6 Processes Each replica has its own Data Protection keys
CryptographicException: The payload was invalid. 6 Processes Keys are shared, but the replicas have different content roots and no SetApplicationName
PendingModelChangesWarning: The model for context 'AppDbContext' has pending changes. 12 Admin processes The model changed but no migration was added; EF Core 9 and later throw instead of migrating

How I Tested It

One ASP.NET Core project (net10.0, minimal APIs) applies all twelve factors. A Python script starts the compiled app with different environment variables, sends real HTTP requests, sends the stop signal, and saves the output. The app logs JSON (factor 11), so I shortened the log lines below to level: category: message; the full JSON is shown once in the logging section. No Docker is installed on the test machine: the container image was built with the .NET SDK and inspected as a tarball, not run. On Windows the stop signal is Ctrl+Break, which .NET handles the same way as SIGTERM on Linux.

The 12 Factors in ASP.NET Core at a Glance

Factor ASP.NET Core feature Tested below
1 Codebase One repo per deployable app no (process rule)
2 Dependencies NuGet + packages.lock.json yes: NU1004
3 Config Environment variables, options + ValidateOnStart yes
4 Backing services Connection strings, AddHttpClient + resilience yes: retries counted
5 Build, release, run SDK container publish, image tag per commit yes: image built and inspected
6 Processes No in-memory state; shared Data Protection keys yes: 4 key setups
7 Port binding Kestrel, ASPNETCORE_HTTP_PORTS yes: precedence
8 Concurrency More replicas, async code no
9 Disposability Graceful shutdown, health probes yes: in-flight request
10 Dev/prod parity Same backing services everywhere no (process rule)
11 Logs AddJsonConsole to stdout yes
12 Admin processes --migrate from the same build yes: 5 at once

Factors 1 and 2: One Codebase, Locked Dependencies

One Git repository per deployable app (a solution with shared class libraries is fine; code copied between repos is not). Dependencies are declared in the project file and nothing is assumed to be installed on the host. Turn on the NuGet lock file so every build restores the same versions:

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <RestorePackagesWithLockFile>true</RestorePackagesWithLockFile>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.14" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.14" PrivateAssets="all" />
    <PackageReference Include="Microsoft.Extensions.Http.Resilience" Version="10.10.0" />
  </ItemGroup>
</Project>

Commit packages.lock.json and restore with --locked-mode in CI. To see what that catches, I changed the resilience package to 10.9.0 in the project file without touching the lock file:

dotnet restore --locked-mode
error NU1004: The package reference Microsoft.Extensions.Http.Resilience version has changed from [10.10.0, ) to [10.9.0, ).The packages lock file is inconsistent with the project dependencies so restore can't be run in locked mode. Disable the RestoreLockedMode MSBuild property or pass an explicit --force-evaluate option to run restore to update the lock file.

The fix is to run a normal dotnet restore locally (it rewrites the lock file) and commit both files together.

Factor 3: Config in the Environment, Validated at Startup

Anything that changes between deploys (connection strings, API keys, bucket names, URLs of other services) comes from the environment, not from a committed appsettings.Production.json. ASP.NET Core reads environment variables after the JSON files, so they override them. Bind the values to an options class and validate it when the app starts:

builder.Services
    .AddOptions<StorageOptions>()
    .BindConfiguration("Storage")
    .ValidateDataAnnotations()
    .ValidateOnStart();

public sealed class StorageOptions
{
    [Required] public string BucketName { get; init; } = "";
    [Required, Url] public string Endpoint { get; init; } = "";
    public int MaxUploadMb { get; init; } = 25;
}

Started with no Storage settings at all, the app never listens on a port. It exits with:

Unhandled exception. Microsoft.Extensions.Options.OptionsValidationException: DataAnnotation validation failed for 'StorageOptions' members: 'BucketName' with the error: 'The BucketName field is required.'.; DataAnnotation validation failed for 'StorageOptions' members: 'Endpoint' with the error: 'The Endpoint field is required.'.

With Storage__Endpoint=s3-example (no scheme) the [Url] check stops it too:

Unhandled exception. Microsoft.Extensions.Options.OptionsValidationException: DataAnnotation validation failed for 'StorageOptions' members: 'Endpoint' with the error: 'The Endpoint field is not a valid fully-qualified http, https, or ftp URL.'.

That is what you want in Kubernetes: the new pod crashes at once, the rollout stops, and the old pods keep serving. Without ValidateOnStart the same mistake shows up later as an exception inside the first request that reads the options.

Nested keys use a double underscore in variable names. The colon form (Storage:BucketName) worked when I passed it to the process from Python on Windows, but a shell won’t create it:

bash: line 1: export: `Storage:BucketName=x': not a valid identifier
ok: prod-uploads

The second line is export Storage__BucketName=prod-uploads, which works everywhere, and the app then answers Bucket: prod-uploads. Connection strings follow the same rule: ConnectionStrings__Default. For real secrets, put a vault (Azure Key Vault, AWS Secrets Manager) behind IConfiguration; the code above doesn’t change.

Factor 4: Backing Services Are Attached Resources

The database, cache, queue and other HTTP services are addressed only through configuration, so swapping a local database for a managed one is a config change:

builder.Services.AddDbContext<AppDbContext>(o =>
    o.UseSqlite(builder.Configuration.GetConnectionString("Default")));

builder.Services.AddHttpClient("pricing", c =>
        c.BaseAddress = new Uri(builder.Configuration["Services:Pricing"] ?? "http://localhost:5999"))
    .AddStandardResilienceHandler();

Attached resources fail for short periods, and AddStandardResilienceHandler() handles that with retries, a circuit breaker and timeouts (10 seconds per attempt by default; it retries 408, 429 and 5xx responses). I pointed Services__Pricing at a small local server that answers 503 twice and then 200:

GET /price -> (200, '200 after 4383 ms')
pricing service hits (s after call): [0.23, 0.39, 4.38]

The caller got a 200; the two failures cost about 4 seconds of retry delay. Keep that in mind when you set your own request timeout. HttpClient setup in more detail: HttpClient in .NET 10 with IHttpClientFactory.

Factor 5: Build Once, Release With Config, Run

The build produces one immutable artifact; the release combines it with environment-specific config; the run stage starts it. For containers, the .NET SDK can build the image itself, without a Dockerfile and without Docker installed:

dotnet publish -c Release -t:PublishContainer -p:ContainerArchiveOutputPath=../artifacts/image/app.tar.gz -p:ContainerImageTag=abc123
Building image 'app' with tags 'abc123' on top of base image 'mcr.microsoft.com/dotnet/aspnet:10.0'.

Tag with the commit SHA (here abc123) instead of latest, so a rollback is redeploying an older tag. I opened the tarball and read the image config; the defaults already fit a 12-factor app (non-root user, port from an environment variable):

"User": "1654",
"ASPNETCORE_HTTP_PORTS=8080",
"DOTNET_RUNNING_IN_CONTAINER=true",
"8080/tcp": {}
"Entrypoint": [
"dotnet",
"/app/App.dll"
"WorkingDir": "/app/"

Omit ContainerArchiveOutputPath to push to a local Docker daemon, or set ContainerRegistry to push to a registry. If you prefer a Dockerfile, see how to Dockerize an ASP.NET Core app.

Factor 6: Stateless Processes (and the Data Protection Trap)

Nothing the app needs later may live only in one process: no in-memory session state, no files on the container disk, no IMemoryCache as the only copy of data. The easy one to miss is ASP.NET Core Data Protection, which encrypts auth cookies and antiforgery tokens. By default the keys live in the user profile of the machine (in a container: inside that container), so every replica has its own. I ran two copies of the app (“pod A” and “pod B”), encrypted a value on A and decrypted it on B, in four setups:

Setup Pod A Pod B
Separate key folders 200 500 CryptographicException: The key {ba07f11e-...} was not found in the key ring.
Shared key folder, same content root 200 200
Shared key folder, different content root 200 500 CryptographicException: The payload was invalid.
Shared key folder + SetApplicationName("my-api"), different content root 200 200

The third row surprised me. Sharing the keys is not enough: without an application name, Data Protection isolates apps by their content root path, so two copies in different folders can’t read each other’s cookies even with the same keys. Replicas of one container image all run from /app/, so this bites when paths differ: blue/green folders on a VM, two IIS sites, or an image whose working directory changed between releases. Set the name every time:

var dp = builder.Services.AddDataProtection();
if (builder.Configuration["DataProtection:KeysPath"] is { } keysPath)
    dp.PersistKeysToFileSystem(new DirectoryInfo(keysPath));
if (builder.Configuration["DataProtection:AppName"] is { } appName)
    dp.SetApplicationName(appName);

In the test the shared store is a folder; in a cluster use a shared volume, Redis (PersistKeysToStackExchangeRedis), Azure Blob Storage or a database, and protect the keys at rest. With one replica none of this shows up, which is why it usually appears on the day you scale to two.

Factor 7: Port Binding

The app is its own web server (Kestrel) and listens on a port it is given. Which variable wins matters, because a wrong port means a pod that is “running” but gets no traffic. What the app bound to, and the warnings it logged:

Environment Listening on
nothing set http://localhost:5000
ASPNETCORE_HTTP_PORTS=8080 (what the official images set) http://[::]:8080
HTTP_PORTS=8080 + ASPNETCORE_URLS=http://+:5102 5102 only
HTTP_PORTS=8080 + ConfigureKestrel(ListenAnyIP(PORT)) the PORT value only
warn: Microsoft.AspNetCore.Hosting.Diagnostics: Overriding HTTP_PORTS '8080' and HTTPS_PORTS ''. Binding to values defined by URLS instead 'http://+:5102'.
warn: Microsoft.AspNetCore.Server.Kestrel: Overriding address(es) 'http://*:8080'. Binding to endpoints defined via IConfiguration and/or UseKestrel() instead.

Note the first row: outside a container, with no variables, the app listens on localhost only, which other machines can’t reach. If your platform injects PORT (Cloud Run, Heroku), read it explicitly:

if (Environment.GetEnvironmentVariable("PORT") is { } port)
    builder.WebHost.ConfigureKestrel(k => k.ListenAnyIP(int.Parse(port)));

Factor 8: Concurrency

Scale out by running more processes, not by making one process bigger. Because the processes are stateless (factor 6), an orchestrator can run any number of replicas behind a load balancer. Inside a process, use async/await all the way down so one replica serves many requests at once. A BackgroundService runs in every replica, so make its work safe to run more than once at the same time (idempotent jobs, a queue, or a lock).

Factor 9: Disposability: Fast Startup, Graceful Shutdown

Kubernetes sends SIGTERM, waits (30 seconds by default), then kills the process. ASP.NET Core stops accepting new connections and lets running requests finish, up to HostOptions.ShutdownTimeout. Keep that timeout below the platform’s grace period:

builder.Services.Configure<HostOptions>(o => o.ShutdownTimeout = TimeSpan.FromSeconds(20));

To check it, I started a request to an endpoint that takes 5 seconds and sent the stop signal 1 second later:

signal (CTRL_BREAK) sent at 1.0s
new request after signal: (None, 'URLError: <urlopen error [WinError 10061] No connection could be made because the target machine actively refused it>')
/slow result: (200, 'done') at 5.02s
process exit code 0 at 5.6s
info: Program: Slow request started
info: Microsoft.Hosting.Lifetime: Application is shutting down...
info: App: ApplicationStopping fired
info: Program: Slow request finished
info: Microsoft.AspNetCore.Hosting.Diagnostics: Request finished HTTP/1.1 GET http://localhost:5105/slow - 200 - text/plain;+charset=utf-8 5019.4385ms
info: OutboxProcessor: Outbox processor stopped gracefully

The request that was already running got its 200; a new connection was refused right away; the background service stopped after the request finished, and the process exited with code 0. The background service stops quickly only because it passes stoppingToken to Task.Delay; a loop that ignores the token holds the shutdown until the timeout.

The platform also needs to know when a replica is ready. Use two endpoints: liveness checks nothing (the process answers), readiness checks the database:

builder.Services.AddHealthChecks()
    .AddCheck<DbHealthCheck>("db", tags: ["ready"]);

app.MapHealthChecks("/healthz/live", new() { Predicate = _ => false });
app.MapHealthChecks("/healthz/ready", new() { Predicate = r => r.Tags.Contains("ready") });
before migration: live (200, 'Healthy') ready (503, 'Unhealthy')
after migration: live (200, 'Healthy') ready (200, 'Healthy')

Never put the database check in liveness: if the database goes down, every pod fails liveness, Kubernetes restarts all of them, and a database problem becomes a full outage. More on probes: ASP.NET Core health checks on .NET 10.

Factor 10: Dev/Prod Parity

Run the same kind of backing services in development as in production. SQLite or the EF Core in-memory provider locally with PostgreSQL in production hides differences in SQL, transactions and case sensitivity until after the deploy. (The test app here uses SQLite because it is a throwaway demo.) Docker Compose, .NET Aspire or Testcontainers give you the production database engine locally and in integration tests.

Factor 11: Logs as Event Streams

Write events to stdout and let the platform collect them; never write or rotate log files inside the container. Switch the console logger to JSON:

builder.Logging.ClearProviders();
builder.Logging.AddJsonConsole(o =>
{
    o.IncludeScopes = true;
    o.TimestampFormat = "O";
    o.UseUtcTimestamp = true;
});

Then I logged the same order twice, once with a message template and once with string interpolation:

log.LogInformation("Order {OrderId} created for customer {CustomerId} totalling {Total}",
    order.Id, order.CustomerId, order.Total);
log.LogInformation($"Order {order.Id} created for customer {order.CustomerId} totalling {order.Total}");

The template version (first) gives the log store fields it can filter on; the interpolated version (second) has the same text but no fields:

"Message": "Order 1001 created for customer C-7 totalling 49.9",
"State": {
"OrderId": 1001,
"CustomerId": "C-7",
"Total": 49.9,
"{OriginalFormat}": "Order {OrderId} created for customer {CustomerId} totalling {Total}"
},

"Message": "Order 1001 created for customer C-7 totalling 49.9",
"State": {
"{OriginalFormat}": "Order 1001 created for customer C-7 totalling 49.9"
},

With IncludeScopes every line also carries TraceId, SpanId and RequestPath, which links logs to traces. Next steps: OpenTelemetry in .NET or Serilog.

Factor 12: Admin Processes From the Same Build

One-off tasks such as database migrations run as separate processes from the same image, with the same config. In the app, a command-line flag runs the migrations and exits without starting the web server:

if (args.Contains("--migrate"))
{
    using var host = builder.Build();
    using var scope = host.Services.CreateScope();
    var log = scope.ServiceProvider.GetRequiredService<ILogger<Program>>();
    var started = DateTime.UtcNow;
    await scope.ServiceProvider.GetRequiredService<AppDbContext>().Database.MigrateAsync();
    log.LogInformation("Migrations applied in {Ms} ms", (int)(DateTime.UtcNow - started).TotalMilliseconds);
    return;
}

Run it as a Kubernetes Job or a pre-deploy step with the same image and the argument --migrate.

The usual argument against Migrate() at startup is that five replicas race to apply the same migration. I tested that: five --migrate processes started at the same moment against one new database. On EF Core 10 there was no race:

## replica 0: exit 0
info: Microsoft.EntityFrameworkCore.Migrations: Acquiring an exclusive lock for migration application. See https://aka.ms/efcore-docs-migrations-lock for more information if this takes too long.
info: Microsoft.EntityFrameworkCore.Migrations: Applying migration '20261027034113_Init'.
info: Program: Migrations applied in 981 ms
## replica 1: exit 0
info: Microsoft.EntityFrameworkCore.Migrations: Acquiring an exclusive lock for migration application. See https://aka.ms/efcore-docs-migrations-lock for more information if this takes too long.
info: Microsoft.EntityFrameworkCore.Migrations: No migrations were applied. The database is already up to date.
info: Program: Migrations applied in 2955 ms

One process applied the migration; the other four waited for the lock (up to 3.9 seconds) and found nothing to do. EF Core 9 added this migration lock. A separate step is still the better design: the app’s database user doesn’t need rights to change the schema, replicas don’t wait on each other at startup, and a failing migration fails one Job instead of crash-looping every pod.

The other EF Core 9+ change you will meet here: if the model changed and you forgot to add a migration, Migrate() throws instead of running. I added a property to an entity without a migration:

Unhandled exception. System.InvalidOperationException: An error was generated for warning 'Microsoft.EntityFrameworkCore.Migrations.PendingModelChangesWarning': The model for context 'AppDbContext' has pending changes. Add a new migration before updating the database. See https://aka.ms/efcore-docs-pending-changes. This exception can be suppressed or logged by passing event ID 'RelationalEventId.PendingModelChangesWarning' to the 'ConfigureWarnings' method in 'DbContext.OnConfiguring' or 'AddDbContext'.

Run dotnet ef migrations add <Name> and commit it; don’t suppress the warning. The other causes (seed data with DateTime.Now, migrations from two merged branches) are in EF Core: the model has pending changes. Upgrade notes for the next version: EF Core 11 breaking changes.

12-Factor Checklist for ASP.NET Core

  • Every deploy-specific value comes from an environment variable (Section__Key), bound to an options class with ValidateOnStart().
  • packages.lock.json committed, dotnet restore --locked-mode in CI.
  • One image per commit, tagged with the SHA, promoted through every environment unchanged.
  • Data Protection keys in a shared store and SetApplicationName set, before the second replica.
  • Only one of ASPNETCORE_HTTP_PORTS, ASPNETCORE_URLS or ConfigureKestrel decides the port; check the “Now listening on” line.
  • ShutdownTimeout shorter than the platform’s grace period; the CancellationToken passed everywhere.
  • Liveness without dependencies, readiness with them.
  • JSON logs to stdout with message templates, not interpolated strings.
  • Migrations as a separate Job from the same image.

The original methodology is at 12factor.net. Microsoft’s references for the parts above: configuration in ASP.NET Core, configuring Data Protection and applying EF Core migrations.

Related: .NET microservices architecture · deploy .NET microservices to AKS · health checks · all ASP.NET Core tutorials

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *