ASP.NET Core host and request flow
ASP.NET Core host and request flow
ASP.NET Core connects an HTTP server to application code through a request pipeline. Kestrel accepts network traffic, middleware handles cross-cutting work, and routing selects an endpoint. The Generic Host owns configuration, dependency injection, logging and application lifetime.
An HTTP request contains a method, target, headers and possibly a body. The server parses it into a request context; middleware may inspect the request, call the next delegate, or finish the response. A route handler is the application function selected by routing. The response travels back through middleware that awaited the next delegate. ASP.NET Core is modern cross-platform .NET web infrastructure, not classic System.Web. Kestrel can serve directly or behind a correctly configured reverse proxy. These tiny programs build a host, start it on a temporary IPv4 loopback port, send requests from the same process, then stop it. The repeated harness is test scaffolding, not production architecture.
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.
Trace one request
A response header and text body make the path observable.
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.Use(async (context, next) =>{ context.Response.Headers["X-Lab"] = "entered"; await next(context);});app.MapGet("/ping", () => "catalog 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 }; using var response = await client.GetAsync("/ping", deadline.Token); Console.WriteLine((int)response.StatusCode); Console.WriteLine(response.Headers.GetValues("X-Lab").Single()); Console.WriteLine(await response.Content.ReadAsStringAsync(deadline.Token));}finally{ using var shutdown = new CancellationTokenSource(TimeSpan.FromSeconds(5)); await app.StopAsync(shutdown.Token);}Middleware sets the header before the endpoint writes the body. The server returns both.
Expected observation (reasoned, not executed):
200enteredcatalog readyShort-circuit a request
A maintenance path can be handled without calling the endpoint.
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.Use(async (context, next) =>{ if (context.Request.Path == "/closed") { context.Response.StatusCode = 503; await context.Response.WriteAsync("maintenance"); return; } await next(context);});app.MapGet("/closed", () => "should not run");app.MapGet("/open", () => "open");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 }; foreach (var path in new[] { "/closed", "/open" }) { using var response = await client.GetAsync(path, deadline.Token); Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync(deadline.Token)}"); }}finally{ using var shutdown = new CancellationTokenSource(TimeSpan.FromSeconds(5)); await app.StopAsync(shutdown.Token);}Returning without calling next prevents endpoint execution. Other requests continue normally.
Expected observation (reasoned, not executed):
503 maintenance200 openObserve request scope
A scoped service is reused inside a request, but new scopes obtain independent instances.
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.Services.AddScoped<Visit>();await using var app = builder.Build();app.MapGet("/scope", (Visit visit, HttpContext context) =>{ var again = context.RequestServices.GetRequiredService<Visit>(); return $"{ReferenceEquals(visit, again)}:{visit.Number}";});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 }; foreach (var path in new[] { "/scope", "/scope" }) Console.WriteLine(await client.GetStringAsync(path, deadline.Token));}finally{ using var shutdown = new CancellationTokenSource(TimeSpan.FromSeconds(5)); await app.StopAsync(shutdown.Token);}sealed class Visit{ private static int next; public int Number { get; } = Interlocked.Increment(ref next);}The first and second sequential requests create separate scoped objects; both resolutions within each request agree.
Expected observation (reasoned, not executed):
True:1True:2Common mistakes and design boundaries
Calling next twice can execute downstream work twice; omitting it accidentally prevents endpoints from running. Set response headers before the response starts. Do not retain HttpContext or scoped dependencies in a singleton. The toy maintenance condition is not an authorization control.
Apply your understanding
Trace a middleware that blocks /offline but permits /catalog and /missing. State expected status codes if only /catalog is mapped.
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
ASP.NET Core host and request flow — knowledge check
Apply the lesson concepts to the following scenarios.
Which component accepts HTTP connections?
What happens when maintenance middleware returns without calling next?
Where should a response header normally be set?
Two requests resolve a scoped service twice each. What is expected?
What does a 200 response from /ping establish?