Module 1 · Hosting and the Request Pipeline · Lesson 1 of 18
How an ASP.NET Core App Starts: WebApplication, the Generic Host and Kestrel
ASP.NET Core starts by building a WebApplication, then starting its Generic Host and HTTP server, usually Kestrel.
The important distinction is between preparing an application and starting it. We will follow a tiny Program.cs, then use a lifecycle probe to see where hosted services and server startup fit.
How do WebApplication, the Generic Host and Kestrel fit together?
These names describe different responsibilities, not three competing ways to run the same thing.
| Part | Its responsibility |
|---|---|
WebApplicationBuilder | Collects configuration, service registrations and hosting settings before the app is built. |
| Generic Host | Coordinates startup and shutdown, as the hosted-service probe below demonstrates. |
WebApplication | Combines control of the host with configuration of request handling and routes. |
| Kestrel | Accepts connections and processes HTTP as the default cross-platform web server. |
Application lifetime means the period from startup through shutdown, including notifications that let services react to those changes.
A hosted service implements IHostedService. The probe below shows the host calling its StartAsync and StopAsync methods. The web server is connected to the Generic Host through a framework-provided hosted service called GenericWebHostService.
flowchart TD
A["WebApplication"] -->|"controls"| B["Generic Host"]
B -->|"starts and stops"| C["GenericWebHostService"]
C -->|"starts and stops"| D["HTTP server: usually Kestrel"]
The diagram shows the lifetime relationship, not the path of an HTTP request.
The mistake to avoid. Do not call Kestrel the host. Kestrel handles HTTP; the Generic Host coordinates the application's resources and lifetime.
In an interview, say: “The Generic Host owns services and application lifetime. WebApplication combines host control with request-pipeline and endpoint configuration. Kestrel is the default cross-platform HTTP server, not the host or the application.”
What does WebApplication.CreateBuilder configure by default?
WebApplication.CreateBuilder(args) gives you a prepared starting point. You customize its defaults rather than assembling all the hosting infrastructure yourself.
A configuration provider reads settings from a particular source. A logging provider sends log messages to a particular destination.
The regular CreateBuilder supplies these defaults:
| Area | Defaults |
|---|---|
| Application configuration | appsettings.json, appsettings.{Environment}.json, Development user secrets when configured, environment variables, then command-line arguments. Later sources override earlier ones for the same key. |
| Host configuration | Includes ASPNETCORE_ and DOTNET_ environment variables and command-line settings for hosting information. |
| Logging | Console, Debug and EventSource providers, plus EventLog on Windows. |
| Dependency injection | The built-in service provider, which creates and supplies registered services. |
| Host lifetime | Console lifetime support, including shutdown requests from Ctrl+C or SIGTERM, an operating-system termination signal. |
| Web hosting | Kestrel configuration and integration with IIS, Microsoft's Windows web server. |
Development adds more than a different settings file:
- User secrets can supply local development settings when the application has a user-secrets ID.
- Service-provider validation checks service construction and incorrect use of scoped services.
- The developer exception page is added automatically, first in the web pipeline. It can display detailed error information.
The developer exception page is middleware: a request-handling component in an ordered chain. We call that chain the request pipeline. The ASP.NET Core Middleware overview explains how these components work together. The developer exception page is middleware, so it becomes useful when the pipeline runs, not when CreateBuilder returns.
Web defaults also include host filtering, which can reject requests with disallowed Host values. Forwarded Headers middleware is off by default. CreateBuilder adds it only when ASPNETCORE_FORWARDEDHEADERS_ENABLED is true. A proxy receives requests and forwards them to your application. This middleware reads headers such as X-Forwarded-For and X-Forwarded-Proto to recover the original client IP address and scheme. Configure which proxies you trust, because anyone can send these headers. See Configure ASP.NET Core to work with proxy servers and load balancers.
See the Generic Host defaults. For configuration precedence and customization, continue with Configuration and the Options Pattern.
The mistake to avoid. Do not assume Development diagnostics are production defaults. Detailed exception pages can expose information, and service validation does not replace testing.
In an interview, say: “CreateBuilder configures settings sources, logging providers, dependency injection, host lifetime and web-server defaults, including Kestrel. Development adds user secrets, service-provider validation and the developer exception page.”
What do Build, Run and StartAsync do?
Here is the anchor program. Run it in an ASP.NET Core project on your own machine. It continues running until you request shutdown.
Before running it, identify which line starts listening.
You can configure listening addresses through ASPNETCORE_URLS, the --urls command-line argument, app.Urls, or Kestrel:Endpoints in configuration. Local development tools can also supply addresses from launchSettings.json. For code-based Kestrel configuration, ListenAnyIP listens on all network interfaces at the specified port.
Without address configuration, Kestrel listens on http://localhost:5000. ASP.NET Core container images configure port 8080 instead. The probe below uses port 0, which asks the operating system to choose an available port. See Configure endpoints for the ASP.NET Core Kestrel web server.
using Microsoft.AspNetCore.Builder;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Hello from ASP.NET Core");
app.Run();Needs ASP.NET Core (a web project). Built with it; not run here.
Follow the program in order:
CreateBuilderprepares the defaults and exposes places to register services and change settings.Buildcreates the application and its service provider. It does not start Kestrel.MapGetregisters an endpoint: a request handler associated with a route and HTTP method. Registering it does not start accepting requests.- The final line calls
app.Run(). The lifetime choices below explain how it differs fromRunAsync()andStartAsync().
There are three common lifetime choices:
| Method | When it returns | Who keeps the application alive? |
|---|---|---|
Run() | After shutdown | The method blocks the calling thread while waiting. |
RunAsync() | Its task completes after shutdown | The caller awaits the application lifetime without blocking a thread for that wait. |
StartAsync() | Its task completes after startup | The caller must keep the process alive and arrange shutdown and disposal. |
Choose Run or RunAsync for the usual application entry point. Choose StartAsync when another part of your program must control the lifetime, as in the next probe. Returning from top-level code immediately after StartAsync is not a substitute for waiting for shutdown.
The WebApplication documentation shows where service registration, middleware and endpoint configuration belong.
The mistake to avoid. Do not treat Build as server startup, or treat StartAsync as a wait-until-shutdown operation. They finish at different points.
In an interview, say: “CreateBuilder prepares defaults and services. Build creates the app and service provider. Run blocks until shutdown; RunAsync awaits that lifetime. I can configure Kestrel addresses through ASPNETCORE_URLS, --urls, launchSettings.json for local development, Kestrel:Endpoints, app.Urls or ListenAnyIP. Without address configuration, Kestrel uses http://localhost:5000.”
Do hosted services start before Kestrel?
WebApplicationBuilder.Build appends the framework's web host service after ordinary service registrations.
Sequential startup means starting services one at a time. In this probe, the hosted service's StartAsync prints a message and returns an already-completed task.
This probe starts and then explicitly stops the application. It uses a system-selected local port and disables framework logging so the lifecycle messages are easy to follow. Run it locally as an ASP.NET Core project.
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
builder.Services.AddHostedService<StartupProbe>();
await using var app = builder.Build();
app.Urls.Add("http://127.0.0.1:0");
app.MapGet("/", () => "Hello");
app.Lifetime.ApplicationStarted.Register(
() => Console.WriteLine("ApplicationStarted"));
app.Lifetime.ApplicationStopping.Register(
() => Console.WriteLine("ApplicationStopping"));
app.Lifetime.ApplicationStopped.Register(
() => Console.WriteLine("ApplicationStopped"));
await app.StartAsync();
Console.WriteLine("Caller: startup completed");
await app.StopAsync();
Console.WriteLine("Caller: shutdown completed");
public sealed class StartupProbe : IHostedService
{
public Task StartAsync(CancellationToken cancellationToken)
{
Console.WriteLine("Probe: StartAsync");
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
Console.WriteLine("Probe: StopAsync");
return Task.CompletedTask;
}
}Needs ASP.NET Core (a web project). Built with it; not run here.
Expected lifecycle messages from a local run, in order:
Probe: StartAsync- Kestrel starts here, before the next message. The probe does not print this internal step.
ApplicationStartedCaller: startup completedApplicationStopping- Kestrel stops here, before the next message. The probe does not print this internal step.
Probe: StopAsyncApplicationStoppedCaller: shutdown completed
The caller's startup message runs after app.StartAsync() completes. The caller then calls app.StopAsync() explicitly.
When the web host service starts, ASP.NET Core first joins your middleware into one request-handling chain. It then starts Kestrel, which can hand requests to that chain. Endpoint routing is the part that selects a registered endpoint for a request. For this minimal application, the framework supplies the routing and endpoint-execution middleware around the mapped handler.
The ordering comes from WebApplicationBuilder's implementation. GenericWebHostService connects pipeline construction to server startup.
This assumes the default service ordering and sequential startup. Concurrent startup or custom registration arrangements can change which startup operations finish first. Starting a background operation also does not mean waiting for all its work to finish.
The mistake to avoid. Do not say “all background initialization finishes before Kestrel starts.” The host awaits the relevant startup methods, not arbitrary work they leave running.
In an interview, say: “By default, hosted services registered through builder.Services start sequentially before the web host service starts Kestrel. A slow StartAsync delays listening. Concurrent startup or custom registration can change completion order.”
How does Kestrel pass requests to the app?
Kestrel handles connections and HTTP processing. It passes each request into the application pipeline using an HttpContext, the object that exposes that request, its response and associated request services.
The pipeline then runs middleware and, when appropriate, the selected endpoint. Kestrel sends the resulting response back over the connection. It does not replace routing or execute controller selection itself.
A reverse proxy is a proxy that receives requests on behalf of an application and forwards them to its server. Kestrel can serve directly, without IIS, or receive forwarded requests from a proxy.
flowchart TD
A["Client"] -->|"sends request"| B["Reverse proxy"]
B -->|"forwards request"| C["Kestrel"]
C -->|"invokes"| D["Application pipeline"]
This diagram shows proxy hosting; direct hosting omits the reverse-proxy step.
IIS uses worker processes (w3wp.exe) to run sites. The ASP.NET Core Module loads your app into an IIS worker process, or forwards requests to Kestrel in a separate process.
IIS supports two different arrangements:
- Out-of-process hosting: IIS forwards requests to Kestrel in a separate application process.
- In-process hosting: the application runs inside the IIS worker process and uses
IISHttpServer, not Kestrel.
In-process hosting has been the default since ASP.NET Core 3.0. It provides better throughput because requests avoid the extra forwarding step to Kestrel. The project hosting-model setting determines what is written to web.config, which the ASP.NET Core Module reads.
A proxy can centralize certificate handling, request filtering and traffic distribution. The cost is another forwarding step and configuration for trusting forwarded request information.
Read the Kestrel overview and IIS in-process hosting for the hosting choices. Continue with The Request Pipeline for what happens after the server hands over a request.
The mistake to avoid. Do not say IIS always sits in front of Kestrel. That describes out-of-process hosting, not IIS in-process hosting.
In an interview, say: “Kestrel can run without IIS. With IIS, in-process hosting is the default since ASP.NET Core 3.0. The app runs inside w3wp.exe using IISHttpServer and avoids an extra forwarding step. Out-of-process hosting uses the ASP.NET Core Module to forward requests to Kestrel in a separate process.”
Does ApplicationStarted mean the application is ready?
ApplicationStarted signals that the application host has fully started. Readiness means the application can currently perform the work you intend to send it.
Those are not the same condition. A cache might still be warming, or a required external dependency might be unavailable. Kestrel can also accept requests before the host raises ApplicationStarted.
Use an explicit readiness condition when traffic depends on initialization outside the awaited startup path. This standalone console example demonstrates such a signal without needing a web server.
A TaskCompletionSource lets one part of a program explicitly complete a task that other code can observe or await.
using System;
using System.Threading.Tasks;
var cacheReady = new TaskCompletionSource<bool>(
TaskCreationOptions.RunContinuationsAsynchronously);
Console.WriteLine($"Before warm-up: ready={cacheReady.Task.IsCompletedSuccessfully}");
// Stand-in for successfully finishing the required cache load.
cacheReady.SetResult(true);
Console.WriteLine($"After warm-up: ready={cacheReady.Task.IsCompletedSuccessfully}");Before warm-up: ready=False After warm-up: ready=True
The check changes from False to True only when the explicit completion signal is set. In an application, set it after successful initialization, not merely after starting the initialization task. The task option makes code waiting on this task (the code after its await) run separately from the SetResult call. Without it, that code can run immediately inside SetResult.
A readiness endpoint can return HTTP 503 while the required condition is false. Configure a load balancer or a Kubernetes readiness probe to call that endpoint. Those checks let the platform stop sending traffic to the app while it is not ready. Dependencies that can fail later may require ongoing checks rather than a one-time signal.
The list of server addresses (app.Urls, or IServerAddressesFeature.Addresses) is not a readiness test: it can describe configured addresses before listening begins. An open port shows that the server is listening, but not that your application can complete useful work.
The mistake to avoid. Do not use an address, an open port or ApplicationStarted as proof that background initialization and external dependencies are ready.
In an interview, say: “ApplicationStarted means host startup completed, not that arbitrary background initialization finished. Kestrel may accept requests before the notification. If traffic depends on something like a warming cache, I use an explicit readiness condition.”
What happens during graceful shutdown?
Graceful shutdown means trying to finish active work and release resources before the process exits.
The probe's shutdown messages follow this order: ApplicationStopping, the probe's StopAsync, then ApplicationStopped. The server's shutdown happens between the first two messages under the default ordering, although the probe does not print that internal step.
The web host service stops before the probe; see the shutdown implementation in Host.StopAsync. Kestrel stops accepting new connections and gives active requests an opportunity to finish. Earlier hosted services then stop, followed by the ApplicationStopped notification.
HostOptions.ShutdownTimeout defaults to 30 seconds. Expiry cancels the token used for shutdown operations. This asks cooperating code to stop waiting or abandon work; it does not forcibly terminate the process. Code that ignores cancellation can keep shutdown running longer. A deployment platform can impose a separate process-termination deadline.
Continue with Background Services and Graceful Shutdown for implementing cancellation correctly.
The mistake to avoid. Do not describe the shutdown timeout as a guaranteed process-kill deadline. Cancellation is a request, not forced termination.
In an interview, say: “The host signals ApplicationStopping. With default ordering, Kestrel drains before earlier hosted services stop in reverse order, then ApplicationStopped fires. ShutdownTimeout defaults to 30 seconds and requests cancellation; it does not kill the process.”
Check yourself
A program calls builder.Build() and app.MapGet(), but never starts the application. What happens?
Show answer
Correct answer: C
Build creates the application, and MapGet registers an endpoint. Starting the host is a separate operation.
ApplicationStarted has fired, but a cache is still warming in the background. Which statement is correct?
Show answer
Correct answer: D
Host startup completion does not prove that arbitrary background initialization has completed.
Going deeper
The ordering in the probe is a default, not a universal hosting contract. In .NET 10, HostOptions.ServicesStopConcurrently defaults to false. Enabling concurrency changes the completion-order assumptions. See HostOptions.cs for the defaults and Host.cs for their use during startup and shutdown.
Development validation also has limits. A scope groups services that share a bounded lifetime, commonly one HTTP request. Scope validation detects invalid scoped-service resolution, including a singleton depending on a scoped service. Build-time validation checks service construction, but it does not prove that an external dependency works. For the detailed rules, see Inside the DI Container.
Finally, these defaults describe the regular WebApplication.CreateBuilder. Slim and empty builders deliberately provide different starting points. Do not transfer the full builder's defaults to them without checking what they configure.
Sources
- ASP.NET Core Middleware | Microsoft Learn: Middleware and the request-handling chain.
- Configure ASP.NET Core to work with proxy servers and load balancers | Microsoft Learn: Forwarded request headers and trusted proxies.
- ASP.NET Core Module (ANCM) for IIS | Microsoft Learn: Loading an in-process application and forwarding to an out-of-process application.
- Configure endpoints for the ASP.NET Core Kestrel web server | Microsoft Learn: Listening addresses, configuration choices and dynamic port binding.
- IHostApplicationLifetime.ApplicationStarted Property | Microsoft Learn: Notification that the application host has fully started.
- .NET Generic Host in ASP.NET Core | Microsoft Learn: Host responsibilities, configuration and logging defaults, web-host defaults, lifetime notifications and graceful shutdown.
- WebApplication and WebApplicationBuilder in ASP.NET Core apps | Microsoft Learn: Builder and application responsibilities, service registration, configuration, endpoint mapping and the Development exception-page default.
- Kestrel web server in ASP.NET Core | Microsoft Learn: Kestrel as the default cross-platform HTTP server and direct versus proxy hosting.
- aspnetcore/src/DefaultBuilder/src/WebApplicationBuilder.cs at release/10.0 · dotnet/aspnetcore · GitHub: Appending GenericWebHostService during Build, automatic pipeline configuration and differences between regular, slim and empty builders.
- aspnetcore/src/Hosting/Hosting/src/GenericHost/GenericWebHostService.cs at release/10.0 · dotnet/aspnetcore · GitHub: Pipeline construction and server startup within the web host service; configured addresses are not a readiness guarantee.
- runtime/src/libraries/Microsoft.Extensions.Hosting/src/HostOptions.cs at release/10.0 · dotnet/runtime · GitHub: Default sequential startup and shutdown settings and the 30-second shutdown timeout.
- runtime/src/libraries/Microsoft.Extensions.Hosting/src/Internal/Host.cs at release/10.0 · dotnet/runtime · GitHub: Awaited hosted-service startup, ApplicationStarted notification, reverse shutdown ordering and cooperative timeout cancellation.
- In-process hosting with IIS and ASP.NET Core | Microsoft Learn: IIS in-process hosting with IISHttpServer versus out-of-process forwarding to Kestrel.
Practice
Checked before publishing: C# examples run on .NET 10, links opened, reviewed while it was written and read in full. How lessons are checked
Updated 28 Nov 2026 ·