ASP.NET Core: The Web Host

ASP.NET Core: The Web Host in C#: A web application is a building with one front door. Behind that door is a reception desk that reads every arriving request,…

The Analogy: The Building and Its Reception

A web application is a building with one front door. Behind that door is a reception desk that reads every arriving request, works out where it should go, and hands it to whoever handles that kind of business. Around the reception is the rest of the building's infrastructure: the electrics, the fire alarm, the directory of who works where, the caretaker who locks up at night. None of that is the work the building does — it is what makes the work possible.

ASP.NET Core splits along exactly this line. Kestrel is the front door: a fast HTTP server that accepts sockets, parses requests and writes responses. Routing is the reception desk, matching the incoming path against a table of endpoints. And the host is the infrastructure — configuration, logging, dependency injection, graceful shutdown — assembled once at startup and available to everything.

The reason this matters more in ASP.NET Core than in older frameworks is that the assembly is explicit and it is yours. A modern Program.cs is a dozen readable lines: create a builder, register the services the application needs, build it, declare the endpoints, run. There is no hidden configuration file deciding which handler receives which URL, and no framework magic wiring up components you did not ask for. What you write is what the building is.

That explicitness has a corollary. If you do not register something, it is not there. There is no authentication until you add it, no HTTPS redirection until you ask for it, no error page until you configure one. The endpoints in this lesson are deliberately open so that the routing is visible on its own — a real service needs the authentication and authorization covered later in this track before it faces the internet.


Syntax or Core Structure

A web project starts from the Web SDK, whose implicit usings already cover the hosting and routing namespaces:

dotnet new web -o Storefront

The whole application is one file. This version starts the host, calls itself with an HttpClient so the responses are visible in the console, and shuts down again:

using System;
using System.Net.Http;
using System.Threading.Tasks;

WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();      // demo only: keeps the console output tidy

WebApplication app = builder.Build();

app.MapGet("/", () => "CodeAcademix API");

app.MapGet("/health", () => Results.Ok(new { status = "ok" }));

// A route constraint: only an integer reaches the handler.
app.MapGet("/orders/{id:int}", (int id) =>
    id == 7
        ? Results.Ok(new { id, sku = "BOLT-01" })
        : Results.NotFound());

app.Urls.Add("http://127.0.0.1:5199");
await app.StartAsync();

using var client = new HttpClient { BaseAddress = new Uri("http://127.0.0.1:5199") };

foreach (string path in new[] { "/", "/health", "/orders/7", "/orders/8", "/nope" })
{
    HttpResponseMessage res = await client.GetAsync(path);
    string body = await res.Content.ReadAsStringAsync();

    Console.WriteLine((int)res.StatusCode + " " + path.PadRight(11) +
                      (body.Length == 0 ? "(no body)" : body));
}

await app.StopAsync();

Output:

200 /          CodeAcademix API
200 /health    {"status":"ok"}
200 /orders/7  {"id":7,"sku":"BOLT-01"}
404 /orders/8  (no body)
404 /nope      (no body)

Four behaviours are on display. Returning a string produced a text/plain response with no ceremony. Returning an object through Results.Ok serialised it as JSON with camelCase property names, which is the web default rather than a coincidence. The {id:int} constraint means /orders/abc never reaches the handler at all — routing declines the match and the response is a 404 produced by the framework, identical in shape to the 404 the handler itself returned for /orders/8. And /nope matched nothing, which is the same 404 again.

The last point is worth dwelling on because it is a common source of confusion when debugging: a 404 can mean "no endpoint matched this path" or "the endpoint matched and decided the resource does not exist", and they are indistinguishable from the outside. When a route mysteriously returns 404, the first question is always whether the endpoint is even being reached — app.MapGet patterns are matched exactly, and a constraint that rejects the value looks identical to a missing resource.

app.StartAsync and app.StopAsync are used here only so the demo can call itself. A real application ends with app.Run(), which starts the host and blocks until the process receives a shutdown signal.


Technical Depth: Builder, Host and Routing

What the builder gives you

WebApplication.CreateBuilder(args) is not a blank slate. Before you touch it, it has already:

  • Loaded configuration from appsettings.json, appsettings.{Environment}.json, user secrets in Development, environment variables and the command line.
  • Configured logging to the console, debug output and event source.
  • Created the dependency injection container and registered the framework's own services.
  • Configured Kestrel, reading URLs from ASPNETCORE_URLS or launch settings.
  • Determined the environment from ASPNETCORE_ENVIRONMENT, defaulting to Production.

builder.Build() returns a WebApplication, which is unusual in implementing three roles at once: it is the IHost (lifetime), the IApplicationBuilder (the middleware pipeline) and the IEndpointRouteBuilder (the route table). That is why app.UseStaticFiles() and app.MapGet(...) are both methods on the same object.

Route templates and constraints

TemplateMatchesNotes
/orders/{id}/orders/7, /orders/abcAny single non-empty segment
/orders/{id:int}/orders/7 onlyType constraint; declines otherwise
/orders/{id:int:min(1)}/orders/7 but not /orders/0Constraints chain with colons
/files/{name}.{ext}/files/logo.pngTwo parameters in one segment
/reports/{*path}/reports/2026/q3/finalCatch-all, slashes included
/orders/{id?}/orders and /orders/7Optional parameter
/orders/{page=1}/orders binds page to 1Default value

Useful built-in constraints include int, long, guid, bool, datetime, decimal, alpha, length(n), minlength(n), maxlength(n), min(n), max(n), range(a,b) and regex(...). They are a routing filter, not validation: they decide whether the endpoint matches, so a rejected value yields 404, not 400. Anything the caller should be told about — a quantity of zero, a malformed email — belongs in the handler as a 400.

Where handler parameters come from

Minimal API handlers are ordinary lambdas or methods, and each parameter is bound from a source inferred by its type and name:

SourceInferred whenExplicit form
Route valuesThe name matches a route parameter[FromRoute]
Query stringA simple type with no route match[FromQuery]
Request bodyA complex type[FromBody]
ServicesThe type is registered in DI[FromServices]
HeadersNever inferred[FromHeader(Name = "X-Trace")]
SpecialHttpContext, HttpRequest, CancellationToken, ClaimsPrincipal, IFormFile-

Only one parameter may come from the body. A nullable or optional parameter makes the value optional; a non-nullable simple type that is missing produces a 400 from the framework before your code runs.

Returning the right response

Results (and its typed twin TypedResults, which is better for testing because the return type names the status) covers the whole vocabulary: Ok, Created, Accepted, NoContent, BadRequest, NotFound, Conflict, Unauthorized, Forbid, File, Redirect, Problem and ValidationProblem. The last two produce an RFC 9457 ProblemDetails document — a standard JSON error shape with type, title, status and detail — which is what a public API should return for errors rather than an ad-hoc object. Register builder.Services.AddProblemDetails() and unhandled failures get the same shape automatically.

Grouping routes

MapGroup factors out a shared prefix, and anything applied to the group applies to every endpoint in it:

RouteGroupBuilder v1 = app.MapGroup("/api/v1")
    .WithTags("v1");                    // metadata, e.g. for OpenAPI

RouteGroupBuilder orders = v1.MapGroup("/orders")
    .RequireAuthorization();            // one call, every endpoint below covered

orders.MapGet("", ListOrders);          // "" maps to the group prefix exactly
orders.MapGet("/{id:int}", GetOrder);

Groups nest, so /api/v1/orders/{id:int} is assembled from three fragments. Note the empty pattern: MapGet("") is the endpoint at the prefix, while MapGet("/") reads as an extra empty segment.

The host's other responsibilities

The environment name drives conditional configuration: app.Environment.IsDevelopment() is how you enable the developer exception page — which prints stack traces and must never be on in production — and how you decide whether to serve a Swagger UI. Kestrel usually sits behind a reverse proxy (IIS, nginx, or a cloud load balancer), in which case UseForwardedHeaders is needed for Request.Scheme and the client IP address to be correct. And IHostApplicationLifetime exposes ApplicationStopping, which is how a service drains in-flight work before the process exits; the host waits a configurable shutdown timeout, thirty seconds by default, for that draining to finish.


Real World Example: The Front Door of a Real Service

A small orders resource, with the four things every HTTP API owes its callers: a versioned prefix, correct status codes, a Location header on creation, and a rejection that explains itself. The store is a dictionary so the example stays runnable; everything else is what production code looks like:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;

WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
builder.Services.AddProblemDetails();

WebApplication app = builder.Build();

var store = new Dictionary<int, Order> { [1] = new Order(1, "BOLT-01", 40) };
int nextId = 2;

// Not authenticated - see the Security module before exposing anything like this.
RouteGroupBuilder orders = app.MapGroup("/api/v1/orders");

orders.MapGet("", () => store.Values.OrderBy(o => o.Id).ToArray());

orders.MapGet("/{id:int:min(1)}", (int id) =>
    store.TryGetValue(id, out Order? found)
        ? Results.Ok(found)
        : Results.NotFound());

orders.MapPost("", (CreateOrder input) =>
{
    // A route constraint cannot say this, so the handler must.
    if (input.Quantity <= 0)
        return Results.BadRequest(new { error = "quantity must be greater than zero" });

    var created = new Order(nextId++, input.Sku, input.Quantity);
    store[created.Id] = created;

    // 201 plus the address of the new resource.
    return Results.Created("/api/v1/orders/" + created.Id, created);
});

orders.MapDelete("/{id:int:min(1)}", (int id) =>
    store.Remove(id) ? Results.NoContent() : Results.NotFound());

app.Urls.Add("http://127.0.0.1:5199");
await app.StartAsync();

using var client = new HttpClient { BaseAddress = new Uri("http://127.0.0.1:5199") };

await Call("GET",    "/api/v1/orders");
await Call("POST",   "/api/v1/orders", new CreateOrder("NUT-02", 10));
await Call("GET",    "/api/v1/orders/2");
await Call("POST",   "/api/v1/orders", new CreateOrder("NUT-02", 0));
await Call("GET",    "/api/v1/orders/99");
await Call("GET",    "/api/v1/orders/0");
await Call("DELETE", "/api/v1/orders/1");
await Call("GET",    "/api/v1/orders");

await app.StopAsync();

async Task Call(string method, string path, object? body = null)
{
    var request = new HttpRequestMessage(new HttpMethod(method), path);
    if (body is not null)
        request.Content = JsonContent.Create(body);

    HttpResponseMessage res = await client.SendAsync(request);
    string text = await res.Content.ReadAsStringAsync();

    Console.WriteLine((int)res.StatusCode + " " + method.PadRight(6) + " " + path.PadRight(20) +
                      (text.Length == 0 ? "(no body)" : text));

    if (res.Headers.Location is not null)
        Console.WriteLine("             location: " + res.Headers.Location);
}

record Order(int Id, string Sku, int Quantity);
record CreateOrder(string Sku, int Quantity);

Output:

200 GET    /api/v1/orders      [{"id":1,"sku":"BOLT-01","quantity":40}]
201 POST   /api/v1/orders      {"id":2,"sku":"NUT-02","quantity":10}
             location: /api/v1/orders/2
200 GET    /api/v1/orders/2    {"id":2,"sku":"NUT-02","quantity":10}
400 POST   /api/v1/orders      {"error":"quantity must be greater than zero"}
404 GET    /api/v1/orders/99   (no body)
404 GET    /api/v1/orders/0    (no body)
204 DELETE /api/v1/orders/1    (no body)
200 GET    /api/v1/orders      [{"id":2,"sku":"NUT-02","quantity":10}]

Every status code in that output is a decision, not a default. 201 with a Location header tells the caller both that the resource was created and where it now lives, which is what lets a client follow up without guessing a URL scheme — and the very next line proves the header is usable by fetching it. 204 on delete says "done, and there is deliberately no body". 200 with an array is the collection. A handler that returned 200 for all four of these would still work, and would push the job of understanding what happened onto every client.

The two 404s came from different places and that is the interesting part. /api/v1/orders/99 reached the handler, which looked in the store and found nothing. /api/v1/orders/0 never reached the handler at all: min(1) declined the route match, so routing produced the 404 itself. This is exactly why constraints are not validation — the caller who passed 0 gets no explanation, whereas the caller who passed a quantity of 0 gets a 400 with a message naming the problem. Use constraints to keep obviously wrong shapes out of your code, and explicit checks for anything the caller deserves to be told.

MapGroup earns its place as soon as there are more than two endpoints. The prefix /api/v1/orders is written once, so a version bump or a rename is one edit rather than four, and cross-cutting concerns attach to the group: RequireAuthorization(), WithTags(...), a rate limiter, an endpoint filter. The alternative — repeating the literal prefix in every Map call — is how APIs end up with one endpoint under /api/v1/order because somebody typed it singular.

Two limitations are deliberate. The store is a Dictionary with a captured nextId, which is fine for a demo and wrong for a server: two concurrent POSTs could receive the same id, because neither Dictionary nor nextId++ is thread-safe. And these endpoints are wide open. Both are addressed later in this track — persistence in the data-access module, and RequireAuthorization with a real scheme in the security module — but it is worth being honest that a runnable example and a production endpoint differ in more than size.


Common Mistakes

  1. Treating route constraints as validation. {quantity:min(1)} rejecting a value produces a bare 404 with no explanation. Anything the caller should be able to correct belongs in the handler as a 400 with a message.
  2. Returning 200 for everything. A creation that answers 200 with no Location, or a delete that answers 200 with an empty body, forces every client to parse the payload to work out what happened. The status code is part of the API.
  3. Leaving the developer exception page on in production. UseDeveloperExceptionPage prints stack traces, source snippets and configuration to anyone who triggers an error. Guard it with app.Environment.IsDevelopment() — the default template already does.
  4. Mutating captured state from handlers. A Dictionary and an int counter captured by a lambda are shared across all concurrent requests with no synchronisation. Handlers run in parallel; anything they touch must be thread-safe or scoped per request.
  5. Asking for a scoped service in a singleton. Injecting a DbContext into a singleton captures one instance for the lifetime of the process. The container will tell you at startup if validation is on; if it is off, you get a very confusing bug instead.
  6. Forgetting UseForwardedHeaders behind a proxy. Request.Scheme reads http, generated links come out wrong, and every client appears to come from the load balancer's address. HTTPS redirection can loop as a result.
  7. Using MapGet("/") inside a group and expecting the prefix. The pattern becomes the prefix plus an empty segment. Use MapGet("") for the endpoint at the group's own path.
  8. Blocking on async work in a handler. .Result or .Wait() inside an endpoint occupies a thread-pool thread for the whole wait and can deadlock in some contexts. Handlers may be async; make them async.

Best Practices

  • Keep Program.cs readable: register services, build, declare endpoints, run. Move handler bodies to named methods or a static class once they outgrow a few lines.
  • Version the API from the first release with a route prefix or a header, and use MapGroup so the version appears in exactly one place.
  • Return the status code that describes what happened, with Location on 201 and no body on 204.
  • Register AddProblemDetails() and return Results.Problem or Results.ValidationProblem for errors, so failures have one machine-readable shape.
  • Use constraints to keep malformed URLs out of your handlers, and explicit checks for business rules the caller needs explained.
  • Take a CancellationToken parameter in any handler that does I/O and pass it down, so an abandoned request stops doing work.
  • Add a /health endpoint (or AddHealthChecks) that reports readiness without authentication, and keep it cheap enough to be polled every few seconds.
  • Handle ApplicationStopping where in-flight work must drain, and keep the shutdown timeout longer than your slowest request.

Practice Exercises

  1. Map the constraint table for yourself. Create endpoints for {id}, {id:int}, {id:int:min(1)}, {code:alpha}, {when:datetime} and {*path}, then call each with a value that should match and one that should not. Record the status code and body for all twelve calls and explain every 404.
  2. Build a complete resource. Write GET, GET by id, POST, PUT and DELETE for a Product under /api/v1/products using MapGroup. Return 201 with Location, 204 from PUT and DELETE, 404 for a missing id, and a 400 that names the offending field. Verify each one with an in-process HttpClient as the example does.
  3. Switch errors to ProblemDetails. Replace the ad-hoc { error = ... } object with Results.ValidationProblem, add AddProblemDetails(), and throw an unhandled exception from a test endpoint. Compare the response body with ASPNETCORE_ENVIRONMENT set to Development and then to Production, and note exactly what stops being disclosed.
  4. Make the store safe. Replace the Dictionary and nextId++ with a ConcurrentDictionary and Interlocked.Increment, then hammer the POST endpoint with fifty parallel requests. Confirm that all fifty ids are distinct, and check what the original version does under the same load.