Middleware Pipeline
Every request in ASP.NET Core travels through a pipeline of small components called middleware. Each middleware can look at the request, do some work, pass the request on to the next middleware, and then look at (or change) the response on the way back out. Exception handling, HTTPS redirection, static files, CORS, authentication and routing are all middleware.
request ──► [Exception handler] ──► [HTTPS redirect] ──► [Auth] ──► [Endpoint]
│
response ◄── [Exception handler] ◄── [HTTPS redirect] ◄── [Auth] ◄──────┘Because each component wraps the next, the order you add them in Program.cs is the order in which they run.
Writing inline middleware with app.Use
app.Use takes a function that receives the HttpContext and a next delegate:
var app = WebApplication.CreateBuilder(args).Build();
app.Use(async (context, next) =>
{
var watch = System.Diagnostics.Stopwatch.StartNew();
context.Response.OnStarting(() =>
{
context.Response.Headers["X-Elapsed-Ms"] = watch.ElapsedMilliseconds.ToString();
return Task.CompletedTask;
});
await next(context); // run the rest of the pipeline
Console.WriteLine(quot;{context.Request.Method} {context.Request.Path} -> {context.Response.StatusCode}");
});
app.MapGet("/hello", () => "Hi!");
app.Run();$ curl -i localhost:5000/helloHTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8
Date: Thu, 16 Oct 2026 09:00:00 GMT
Server: Kestrel
Transfer-Encoding: chunked
X-Elapsed-Ms: 3
Hi!
Note: Headers must be set before the response body starts being sent. That's why the example uses
Response.OnStartinginstead of setting the header afternextreturns — by then the body may already be on the wire.
The pipeline is just nested delegates
There's no magic here. A middleware is a function that takes the next handler and returns a new handler. Build the chain from the end backwards, and you get the "wrap" behaviour. This program is a working mini pipeline:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
var middleware = new List<Func<Handler, Handler>>
{
next => async ctx => // 1. logging
{
ctx.Log.Add(quot;-> {ctx.Path}");
await next(ctx);
ctx.Log.Add(quot;<- {ctx.Status}");
},
next => async ctx => // 2. API key check (can short-circuit)
{
if (ctx.Path.StartsWith("/admin") && ctx.ApiKey != "secret")
{
ctx.Status = 401;
ctx.Log.Add(" auth: rejected");
return; // next is NOT called
}
ctx.Log.Add(" auth: ok");
await next(ctx);
},
};
Handler endpoint = ctx => // 3. the endpoint
{
ctx.Status = 200;
ctx.Log.Add(quot; endpoint handled {ctx.Path}");
return Task.CompletedTask;
};
// Build: wrap the endpoint with the middleware, last one first
Handler app = endpoint;
for (int i = middleware.Count - 1; i >= 0; i--)
app = middleware[i](app);
foreach (var ctx in new[] { new Ctx("/hello", null), new Ctx("/admin", "wrong"), new Ctx("/admin", "secret") })
{
await app(ctx);
Console.WriteLine(string.Join(Environment.NewLine, ctx.Log));
Console.WriteLine();
}
delegate Task Handler(Ctx ctx);
class Ctx(string path, string? apiKey)
{
public string Path { get; } = path;
public string? ApiKey { get; } = apiKey;
public int Status { get; set; }
public List<string> Log { get; } = new();
}-> /hello
auth: ok
endpoint handled /hello
<- 200
-> /admin
auth: rejected
<- 401
-> /admin
auth: ok
endpoint handled /admin
<- 200
ASP.NET Core does exactly this: RequestDelegate is delegate Task RequestDelegate(HttpContext context), and app.Use adds a Func<RequestDelegate, RequestDelegate> to a list that Build() folds together.
Short-circuiting, Run and Map
| Method | What it does |
|---|---|
app.Use(…) |
Middleware that normally calls next (and may choose not to) |
app.Run(context => …) |
Terminal middleware: never calls next; anything added after it never runs |
app.Map("/path", branch => …) |
Branches the pipeline for requests whose path starts with /path |
app.UseWhen(predicate, branch => …) |
Runs extra middleware when the predicate is true, then rejoins the main pipeline |
app.MapWhen(predicate, branch => …) |
Branches when the predicate is true and does not rejoin |
app.UseWhen(ctx => ctx.Request.Path.StartsWithSegments("/api"), api =>
{
api.Use(async (ctx, next) =>
{
ctx.Response.Headers["X-Api-Version"] = "1";
await next(ctx);
});
});Order matters
A typical production pipeline looks like this. Each line is positioned on purpose:
app.UseExceptionHandler(); // 1. outermost: catches exceptions from everything below
app.UseHsts(); // 2. tell browsers to use HTTPS
app.UseHttpsRedirection(); // 3. redirect http -> https
app.UseStaticFiles(); // 4. serve wwwroot files early and cheaply (short-circuits)
app.UseRouting(); // 5. choose the endpoint (added implicitly if omitted)
app.UseCors(); // 6. CORS needs to know the endpoint
app.UseAuthentication(); // 7. who are you?
app.UseAuthorization(); // 8. are you allowed? (needs the user AND the endpoint)
app.UseRateLimiter(); // 9. per-endpoint limits
app.MapControllers(); // 10. endpoints run at the end| Mistake | Symptom |
|---|---|
UseAuthorization() before UseAuthentication() |
Every protected endpoint returns 401 — the user is never identified in time |
| Exception handler added last | Exceptions from earlier middleware are not caught |
Custom logging middleware after UseStaticFiles() |
Requests for CSS/JS never reach your logger |
Middleware classes
For anything non-trivial, write a class. It needs a constructor taking RequestDelegate and a public InvokeAsync(HttpContext) method. Extra parameters of InvokeAsync are resolved from dependency injection per request:
public class RequestIdMiddleware(RequestDelegate next)
{
public async Task InvokeAsync(HttpContext context, ILogger<RequestIdMiddleware> logger)
{
var id = context.Request.Headers["X-Request-Id"].FirstOrDefault() ?? Guid.NewGuid().ToString("N")[..8];
context.Response.Headers["X-Request-Id"] = id;
using (logger.BeginScope("RequestId {RequestId}", id))
{
await next(context);
}
}
}
public static class RequestIdExtensions
{
public static IApplicationBuilder UseRequestId(this IApplicationBuilder app)
=> app.UseMiddleware<RequestIdMiddleware>();
}
// Program.cs
app.UseRequestId();$ curl -s -D - -o /dev/null localhost:5000/hello -H "X-Request-Id: abc123"HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8
Date: Thu, 16 Oct 2026 09:00:00 GMT
Server: Kestrel
Transfer-Encoding: chunked
X-Request-Id: abc123
Tip: Conventional middleware classes are created once (they behave like singletons). Never store per-request data in fields — inject scoped services through
InvokeAsyncparameters instead.
Middleware vs endpoint filters
Middleware runs for every request that reaches it. If logic only concerns a few endpoints (validating one input type, for instance), an endpoint filter (.AddEndpointFilter(...)) is the better tool — the Filters lesson covers it.
Test yourself
In app.Use(async (context, next) => { A; await next(context); B; }), when does B run?
- Before the endpoint
- After the rest of the pipeline (including the endpoint) has finished
- Only when an exception occurs
- Never
Why must UseAuthentication() come before UseAuthorization()?
- Alphabetical order is required
- Authorization needs to know who the user is, which authentication establishes
- Authentication is slower
- It doesn't matter
What does a middleware do to short-circuit the pipeline?
- Throws an exception
- Calls
nexttwice - Writes a response and returns without calling
next - Calls
app.Run()