Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 52 ยท Getting Started

The Host and the Builder

Understand WebApplicationBuilder and WebApplication: what CreateBuilder sets up, how services, configuration, logging and environment fit together, and Use vs Map.

Two objects dominate every Program.cs: the WebApplicationBuilder and the WebApplication it produces. The builder is where you describe the application: which services exist, where configuration comes from, how logging behaves. The application is where you use that description: you add middleware and endpoints and start listening.

This split has one big rule: you configure services on the builder, call Build() once, and then you can no longer change the service container. This lesson shows what each object holds, what CreateBuilder already did for you, and the difference between Use and Map, which trips up many beginners.

Two phases

flowchart LR
    A["Builder<br/>Services, Configuration,<br/>Logging, Environment, WebHost"] --> B["Build()"]
    B --> C["App<br/>Use... middleware<br/>Map... endpoints"]
    C --> D["Run or StartAsync"]

Configure everything on the builder, build once, then describe the request pipeline on the app.

After Build(), the dependency injection container is read-only. app.Services is an IServiceProvider, which can only resolve services, so registering one afterwards does not even compile. The point is simple: a frozen container can be validated, optimized and shared safely between thousands of requests.

What CreateBuilder already did

WebApplication.CreateBuilder(args) is a convenience: it creates the builder and applies the defaults that almost every web app wants. Without it, you would write all of this by hand.

Area Default setup
Web server Kestrel, with URLs from configuration (ASPNETCORE_URLS, --urls, launchSettings.json)
Content root The current directory (where appsettings.json lives)
Configuration appsettings.json, appsettings.{Environment}.json, user secrets (Development only), environment variables, command-line arguments
Logging Console, Debug and EventSource providers, with settings read from the Logging section
Environment From ASPNETCORE_ENVIRONMENT (or DOTNET_ENVIRONMENT), Production if missing
Dependency injection The built-in container, with scope validation turned on in Development
Host filtering AllowedHosts from configuration

Let us look at those pieces from code. The next program inspects a freshly created builder and the built application.

C# What does the builder hold?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The environment name, configuration and services are available on both objects, but you may only add services on the builder. The environments and secrets lesson explains how the environment changes behavior.

Configuring each piece

Services

builder.Services is the IServiceCollection you know from dependency injection. ASP.NET Core also provides AddXxx methods that register whole features: AddControllers(), AddAuthentication(), AddRateLimiter(), AddHealthChecks(), AddOpenApi(). Remember the pattern Add on the builder, Use or Map on the app.

Configuration

builder.Configuration is both a reader and a builder: you can read values and also add sources, such as builder.Configuration.AddJsonFile("extra.json", optional: true). Sources added later override earlier ones. See Configuration and the Options Pattern.

Logging

builder.Logging controls providers and levels. ClearProviders() removes the defaults; SetMinimumLevel(...) and AddFilter(...) change what gets recorded. Our examples call ClearProviders() to keep the output clean, but in real apps you normally keep the console logger. See Logging and Diagnostics.

The web host

builder.WebHost configures Kestrel and the URLs. UseUrls(...) sets the addresses, ConfigureKestrel(...) lets you set limits, certificates and endpoints in code.

Use versus Map

Both names appear on WebApplication, and they do different jobs.

  • app.Use... adds a middleware component to the pipeline. Middleware runs for requests in the order you add it, and usually calls the next component.
  • app.Map... declares an endpoint (or branches the pipeline by path). MapGet runs only when the path and verb match.

Compare these two lines:

C#
app.Use(async (context, next) => { /* runs for every request */ await next(); });
app.MapGet("/hello", () => "hi");   // runs only for GET /hello

The next program shows both in action, with an extra MapGet that is never reached by one of the requests.

C# Use runs for everything, Map only when it matches

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The middleware saw both requests, even the one that ended in a 404. The endpoint ran only for /hello. That is the difference in one picture: middleware wraps everything, endpoints answer specific requests.

Order matters

Middleware executes in the order you add it. Put an error handler first so it can catch problems from everything below it; put authentication before authorization. In this program, the order of two Use calls changes the result, and the second one can end the request without calling next.

C# Order and short-circuiting

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The /blocked endpoint exists but is unreachable because the second middleware answered first. Both responses still carry X-Stage: first, because the first middleware ran before the second. Swap the two Use blocks and the blocked response would lose the header. The middleware pipeline lesson turns this into a full tool.

The implicit pipeline

You might notice that our examples never called UseRouting() or UseEndpoints(). Since .NET 6, WebApplication adds routing and endpoint execution automatically: routing is placed at the start of the pipeline (so middleware can see which endpoint was chosen) and endpoints at the end. You only call UseRouting() yourself when you need to place other middleware relative to it, for example authentication.

Running the host

A few ways to start, with different effects:

Call Behavior
app.Run() Start and block until shutdown. The normal choice.
await app.RunAsync() The same, but awaitable.
await app.StartAsync() Start and return. Pair with StopAsync(). Used in tests and in our examples.
app.Run("http://localhost:6000") Start with explicit URLs.

When the process receives Ctrl+C or SIGTERM, the host shuts down gracefully: it stops accepting new requests, lets running requests finish (up to a timeout) and disposes services. That is why a host is better than a hand-written loop.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where do you register services such as AddSingleton<Clock>()?

    Services are registered on the builder. Build() freezes the container.
  2. 2. What is the difference between app.Use(...) and app.MapGet(...)?

    Middleware wraps requests (often every request); an endpoint answers only the requests whose path and method match.
  3. 3. A middleware does not call next() and writes a response. What happens to later middleware and endpoints?

    Not calling next short-circuits the pipeline, so nothing after it runs for that request.
  4. 4. Which environment does the host assume if ASPNETCORE_ENVIRONMENT is not set?

    The default is Production, which is the safe choice because it hides detailed error pages.
  5. 5. Why does app.MapGet work without calling UseRouting()?

    Since .NET 6, WebApplication wires routing and endpoint middleware for you. Call UseRouting explicitly only to control the position of other middleware.

Summary

  • The builder describes the app (services, configuration, logging, environment, web host); Build() freezes the service container; the app holds the pipeline.
  • CreateBuilder applies the standard defaults: Kestrel, layered configuration, console logging, environment detection and DI.
  • Add on the builder (AddXxx), use on the app (UseXxx for middleware, MapXxx for endpoints).
  • Middleware runs in the order added and can short-circuit by not calling next().
  • Routing and endpoint execution are added automatically; call UseRouting() only to place middleware relative to it.
  • Run() blocks until graceful shutdown; StartAsync() and StopAsync() suit tests and our examples.

Next: Minimal API Endpoints