Hosting configuration and lifetime
Hosting configuration and lifetime
The host manages application startup, service configuration and shutdown. Kestrel binding determines which network interfaces accept connections. Development configuration is useful for local work, but production settings must be selected and verified independently.
Configuration combines providers, with later providers normally winning for matching keys. The hosting environment name affects environment-specific behavior, not the security of an app by itself. A listener bound to 127.0.0.1 is reachable from the local network namespace only; it is not the same as a wildcard bind. A reverse proxy or other local process may still reach it. Port zero requests an available port from the OS. For a manually served demo use a reviewed project and dotnet run --no-launch-profile -- --urls http://127.0.0.1:5080 if it uses URL configuration rather than explicit Listen endpoints. Launch profiles are development tooling, not deployment policy. The examples below use explicit Listen and stop automatically; the extra --urls flag is unnecessary for them.
Baseline: .NET 10 / C# 14. Each code block is an independent static example with a companion Web SDK project. Read the endpoint registration and client checks first; the surrounding host harness is repeated for standalone use. Expected observations are reasoned, not executed. Run only in a clean, isolated local environment with an approved SDK; no launch profile, external network or real data. The OpenAPI package example additionally requires approved restore.
Read an explicit lab setting
The in-memory configuration contains non-sensitive data; do not dump all configuration.
using System.Net;using System.Net.Http.Json;using System.Text;using System.Text.Json;using Microsoft.AspNetCore.Http.HttpResults;using Microsoft.AspNetCore.Mvc;
// Standalone lab: run in a clean, isolated environment only.var builder = WebApplication.CreateBuilder(new WebApplicationOptions{ Args = Array.Empty<string>(), EnvironmentName = "Production", ContentRootPath = AppContext.BaseDirectory});builder.Configuration.Sources.Clear();builder.Logging.ClearProviders();builder.WebHost.ConfigureKestrel(options =>{ options.Listen(IPAddress.Loopback, 0); options.Limits.MaxRequestBodySize = 16 * 1024;});builder.Configuration.AddInMemoryCollection(new Dictionary<string, string?> { ["Catalog:Label"] = "Default" });builder.Configuration.AddInMemoryCollection(new Dictionary<string, string?> { ["Catalog:Label"] = "Training catalog" });await using var app = builder.Build();app.MapGet("/label", () => app.Configuration["Catalog:Label"] ?? "unset");using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(15));await app.StartAsync(deadline.Token);try{ var address = new Uri(app.Urls.Single()); if (address.Host != "127.0.0.1" || address.Scheme != "http") throw new InvalidOperationException("Unexpected listener address."); using var client = new HttpClient(new HttpClientHandler { UseProxy = false, AllowAutoRedirect = false }) { BaseAddress = address }; Console.WriteLine(await client.GetStringAsync("/label", deadline.Token));}finally{ using var shutdown = new CancellationTokenSource(TimeSpan.FromSeconds(5)); await app.StopAsync(shutdown.Token);}A later configuration value overrides the earlier one for the same key.
Expected observation (reasoned, not executed):
Training catalogVerify the actual local binding
Read the assigned address only after startup; never require a particular dynamic port.
using System.Net;using System.Net.Http.Json;using System.Text;using System.Text.Json;using Microsoft.AspNetCore.Http.HttpResults;using Microsoft.AspNetCore.Mvc;
// Standalone lab: run in a clean, isolated environment only.var builder = WebApplication.CreateBuilder(new WebApplicationOptions{ Args = Array.Empty<string>(), EnvironmentName = "Production", ContentRootPath = AppContext.BaseDirectory});builder.Configuration.Sources.Clear();builder.Logging.ClearProviders();builder.WebHost.ConfigureKestrel(options =>{ options.Listen(IPAddress.Loopback, 0); options.Limits.MaxRequestBodySize = 16 * 1024;});await using var app = builder.Build();app.MapGet("/ready", () => "ready");using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(15));await app.StartAsync(deadline.Token);try{ var address = new Uri(app.Urls.Single()); if (address.Host != "127.0.0.1" || address.Scheme != "http") throw new InvalidOperationException("Unexpected listener address."); using var client = new HttpClient(new HttpClientHandler { UseProxy = false, AllowAutoRedirect = false }) { BaseAddress = address }; Console.WriteLine(client.BaseAddress!.Host); Console.WriteLine(client.BaseAddress.Port > 0); Console.WriteLine(await client.GetStringAsync("/ready", deadline.Token));}finally{ using var shutdown = new CancellationTokenSource(TimeSpan.FromSeconds(5)); await app.StopAsync(shutdown.Token);}The address is loopback with an OS-assigned nonzero port.
Expected observation (reasoned, not executed):
127.0.0.1TruereadyObserve stopping notification
ApplicationStopping is a cancellation signal, not proof all cleanup has finished.
using System.Net;using System.Net.Http.Json;using System.Text;using System.Text.Json;using Microsoft.AspNetCore.Http.HttpResults;using Microsoft.AspNetCore.Mvc;
// Standalone lab: run in a clean, isolated environment only.var builder = WebApplication.CreateBuilder(new WebApplicationOptions{ Args = Array.Empty<string>(), EnvironmentName = "Production", ContentRootPath = AppContext.BaseDirectory});builder.Configuration.Sources.Clear();builder.Logging.ClearProviders();builder.WebHost.ConfigureKestrel(options =>{ options.Listen(IPAddress.Loopback, 0); options.Limits.MaxRequestBodySize = 16 * 1024;});await using var app = builder.Build();using var registration = app.Lifetime.ApplicationStopping.Register(() => Console.WriteLine("stopping"));app.MapGet("/state", () => "running");using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(15));await app.StartAsync(deadline.Token);try{ var address = new Uri(app.Urls.Single()); if (address.Host != "127.0.0.1" || address.Scheme != "http") throw new InvalidOperationException("Unexpected listener address."); using var client = new HttpClient(new HttpClientHandler { UseProxy = false, AllowAutoRedirect = false }) { BaseAddress = address }; Console.WriteLine(await client.GetStringAsync("/state", deadline.Token));}finally{ using var shutdown = new CancellationTokenSource(TimeSpan.FromSeconds(5)); await app.StopAsync(shutdown.Token);}The harness stops the host in finally, triggering the registered callback before shutdown completes.
Expected observation (reasoned, not executed):
runningstoppingCommon mistakes and design boundaries
Never bind to all interfaces merely to fix a local development issue. Do not expose developer exception details to clients. A shutdown signal is cooperative; a crash or forced termination can skip cleanup. Keep stop callbacks short and use a separate shutdown deadline.
Apply your understanding
A catalog app must be accessible only from its own machine during development. Describe binding, configuration precedence, and shutdown verification.
Complete the linked manual practice and knowledge check. The examples are not automated ByteMind assessments.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Hosting configuration and lifetime — knowledge check
Apply the lesson concepts to the following scenarios.
Which binding limits an IPv4 listener to local loopback?
What does port 0 request when using Listen on a specific IP?
Two in-memory providers set the same key. Which value is used?
What does ApplicationStopping indicate?
What can prevent cleanup even with a correct StopAsync handler?