skip to content

In ASP.NET Core 10, why does builder.Host.UseEnvironment("Staging") throw after WebApplication.CreateBuilder, and how does WebApplicationOptions solve it?

level: middleimportance: should knowfreq 38%

answer

  1. decided inside the builder's constructor
  2. NotSupportedException, not a silent change
  3. Args, EnvironmentName, ApplicationName
  4. ContentRootPath, WebRootPath, init-only
  5. ASP0008, ASP0009, ASP0010 analyzers

basics

~10 s

CreateBuilder fixes the environment, content root, web root and application name while it is constructed, so builder.Host or builder.WebHost changing them throws NotSupportedException. Pass them up front in WebApplicationOptions to CreateBuilder instead.

solid answer

~40 s

`WebApplicationBuilder` does its host setup eagerly: by the time `CreateBuilder` returns, it has resolved the environment name, loaded `appsettings.{Environment}.json`, created `IWebHostEnvironment` and set the content and web roots. `builder.Host` (`ConfigureHostBuilder`) and `builder.WebHost` (`ConfigureWebHostBuilder`) run your callbacks immediately and then compare those settings; if the application name, content root, environment or web root changed, they throw `NotSupportedException` telling you to use `WebApplication.CreateBuilder(WebApplicationOptions)`. `WebApplicationOptions` has five init-only properties — `Args`, `EnvironmentName`, `ApplicationName`, `ContentRootPath`, `WebRootPath` — applied before anything is loaded, and overriding environment variables and arguments for those keys. The same adapters also refuse `Build()`, `Configure()`, `UseStartup()` and `ConfigureWebHost()`, which analyzers ASP0008-ASP0010 flag at compile time.

code

csharp · 12 lines
csharp
var builder = WebApplication.CreateBuilder(new WebApplicationOptions
{
    Args = args,
    EnvironmentName = Environments.Staging,
    ContentRootPath = AppContext.BaseDirectory,
    WebRootPath = "public"
});

// builder.Host.UseEnvironment("Staging");   // would throw NotSupportedException

var app = builder.Build();
app.Run();

go deeper

for a junior

Recall that environment, content root and web root are set through WebApplicationOptions passed to CreateBuilder, not changed on builder.Host afterwards.

for a middle

Explain that the builder decides those settings eagerly in its constructor, so the Host and WebHost adapters detect changes and throw NotSupportedException.

for a senior

Port Generic Host chains safely: move identity settings into options, keep container and library hooks on builder.Host, and watch inline callback ordering.

for a principal

Set conventions for alternative entry points such as smoke tests and tools, so environment and paths are explicit rather than inherited from machine variables.

## Why the old way throws With the Generic Host, `Host.CreateDefaultBuilder(args)` only **collected** callbacks; nothing ran until `Build()`. Calling `.UseEnvironment("Staging")` anywhere in the chain simply changed what the deferred code would later see. `WebApplicationBuilder` is different. Its constructor does the work **eagerly** so that the imperative code underneath can observe it: it builds host configuration, decides the **environment name**, **application name** and **content root**, loads `appsettings.json` and `appsettings.{Environment}.json`, creates `IWebHostEnvironment` (`builder.Environment`) and sets the **web root**. By the time `builder.Host` is reachable, decisions that depend on the environment have already been made. So `builder.Host` and `builder.WebHost` are adapters with a guard: 1. `ConfigureHostBuilder.ConfigureHostConfiguration` runs your callback, and `ConfigureWebHostBuilder.UseSetting` applies your value, **immediately** against the live configuration; 2. they compare the application name, content root, environment (and, on `WebHost`, the web root and hosting-startup assemblies) before and after; 3. if any changed, they throw `NotSupportedException` with a message such as *"The environment changed from "Production" to "Staging". Changing the host configuration using WebApplicationBuilder.Host is not supported. Use WebApplication.CreateBuilder(WebApplicationOptions) instead."* `UseEnvironment`, `UseContentRoot` and `UseWebRoot` are thin wrappers over those methods, which is why they throw. ## The fix: WebApplicationOptions `WebApplicationOptions` carries the settings the builder needs **before** it does anything: | Property | Sets | Typical use | |---|---|---| | `Args` | Command-line arguments | Always pass `args` through | | `EnvironmentName` | `IWebHostEnvironment.EnvironmentName` | Force `Staging` for a smoke-test host | | `ApplicationName` | `IHostEnvironment.ApplicationName` | Point user secrets or assembly scanning at another assembly | | `ContentRootPath` | Where `appsettings*.json` are found | Running from a service manager with an odd working directory | | `WebRootPath` | Static-file root (default `wwwroot`) | A front-end build output folder | All five are `init`-only, so they are set in an object initializer and never changed afterwards. The builder hands `EnvironmentName`, `ApplicationName` and `ContentRootPath` to `HostApplicationBuilderSettings`, which apply them **after** environment variables and command-line arguments for those keys — the options win. `WebRootPath` is added as an in-memory configuration value. ## Other calls the adapters refuse The adapters exist so that libraries written against `IHostBuilder` and `IWebHostBuilder` extension methods keep working — `builder.Host.UseServiceProviderFactory(...)` for a third-party container, `builder.WebHost.ConfigureKestrel(...)` for server limits. Calls that would start a second composition root are refused outright: - `builder.Host.Build()` and `builder.WebHost.Build()` → `NotSupportedException` ("Call WebApplicationBuilder.Build() instead"); - `builder.WebHost.Configure(...)` → `NotSupportedException`; analyzer **ASP0009**; - `builder.WebHost.UseStartup<T>()` → `NotSupportedException`; analyzer **ASP0010**; - `builder.Host.ConfigureWebHost(...)` → `NotSupportedException`; analyzer **ASP0008**. Two related analyzers only suggest: **ASP0012** prefers `builder.Services` over `Host.ConfigureServices`, and **ASP0011** prefers `builder.Logging`. ## Callbacks run inline Because the adapters run callbacks immediately, ordering follows the source text. `builder.Host.ConfigureServices((ctx, s) => s.AddSingleton<IService, Service1>())` followed by `builder.Services.AddSingleton<IService, Service2>()` registers `Service1` first and `Service2` second — with the Generic Host the deferred callback would have run later. Code ported from `Host.CreateDefaultBuilder` that relied on deferral can change which registration wins. ## When this comes up - A smoke-test or tooling entry point that must run as `Staging` regardless of the machine's variables. - A Windows service whose working directory is the system folder, where `ContentRootPath = AppContext.BaseDirectory` makes `appsettings.json` findable. - Migrating from `Startup` code where `UseContentRoot` or `UseEnvironment` sat in the builder chain — they move into the options object. ## Reading the failure The exception surfaces on the line that made the change, during startup, so it is easy to diagnose once recognised: 1. The type is `NotSupportedException`, thrown from `ConfigureHostBuilder` or `ConfigureWebHostBuilder`. 2. The message names **what** changed and the old and new values — environment, content root, application name, web root, or hosting-startup assemblies. 3. The message's last sentence is the fix: use `WebApplication.CreateBuilder(WebApplicationOptions)`. A library extension method can trigger it too — one that calls `UseContentRoot` internally will throw even though `Program.cs` never mentions the content root. The stack trace shows which extension made the call. Settings that are **not** guarded remain configurable on the adapters: `builder.WebHost.UseSetting("urls", ...)`, `builder.WebHost.ConfigureKestrel(...)` and ordinary configuration keys can still be changed after `CreateBuilder` returns.

  • Which WebApplicationBuilder.Host calls are still fine to use in ASP.NET Core 10?
    Calls that do not change host identity or build anything: `UseServiceProviderFactory` for a third-party container, `ConfigureContainer`, `ConfigureAppConfiguration`, `ConfigureServices`, and library extension methods built on them. They run inline, so their effects are visible to the next line of `Program.cs`.
  • Does WebApplicationOptions.EnvironmentName win over ASPNETCORE_ENVIRONMENT?
    Yes. The builder passes it through `HostApplicationBuilderSettings`, whose values are applied after environment-variable and command-line sources for the same keys, so the options value is what `builder.Environment.EnvironmentName` reports.

  • builder.Host.UseEnvironment works the same way it did on Host.CreateDefaultBuilder
  • builder.WebHost.UseContentRoot is the supported way to move appsettings.json
  • WebApplicationOptions properties can be changed after CreateBuilder returns
  • builder.Host.ConfigureServices callbacks are deferred until Build
  • builder.WebHost.UseStartup<Startup>() is the bridge for existing Startup classes