Skip to content
Tutorials Center
My learning

Topics

Lesson 137 of 182 ยท ASP.NET Core

Middleware and the Request Pipeline

Learn ASP.NET Core middleware in C# - the request pipeline, Use, Run and Map, ordering, short-circuiting, middleware classes, exception handling, request logging and endpoint filters.

Every HTTP request that reaches an ASP.NET Core application passes through a chain of small components before a response goes back. One component checks whether the caller is logged in, another compresses the response, another turns an unhandled exception into a clean error page, and at the end of the chain sits the code that actually answers the request: your endpoint. Those components are called middleware, and the chain is the request pipeline.

Understanding the pipeline explains a lot of behavior that otherwise feels like magic: why the order of app.UseXxx() calls matters, why a request sometimes never reaches your endpoint, and where cross-cutting concerns such as logging, error handling and authentication live. In this lesson you will build a pipeline from scratch with Use, Run and Map, write middleware as a class, handle exceptions in one place, log requests, and then meet endpoint filters, the same idea applied to a single endpoint. If you have not served a minimal API yet, read ASP.NET Core Overview and Minimal APIs first.

All examples start a real Kestrel server on a loopback address inside the program and call it with HttpClient, then stop it. The using lines at the top of each example are what a web project adds for you automatically (the Web SDK has its own implicit usings), but our single-file runner needs them spelled out. That is how our runner can show a whole web server in one file. In a real project you would write the same app.Use... lines in Program.cs and run dotnet run.

The pipeline as a chain of delegates

Think of the pipeline as a set of nested calls. Each middleware receives the HttpContext (the request and the response) and a next delegate that runs the rest of the pipeline. A middleware can do work before calling next, call it (or not), and do more work after it returns. The response flows back out through the same components in reverse order, like a function call stack.

TEXT
request  -->  [ middleware A ] -->  [ middleware B ] -->  [ endpoint ]
response <--  [ middleware A ] <--  [ middleware B ] <--  [ endpoint ]

The simplest way to write a middleware is app.Use(...) with a lambda. The following program adds two of them and a final endpoint. Watch the order of the printed lines:

C# Before and after next

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 output shows A: before, B: before, endpoint runs, B: after, A: after. The request goes in through A, then B, then the endpoint; the unwinding happens in reverse. Each await next(context) is the point where control passes deeper.

The await matters. If you forget it, next starts but your code continues immediately, the "after" code runs too early, and the response may already be sent when later components try to change it. Always await next(context) (the older next() overload without a parameter also works but allocates a closure and is discouraged in new code).

Use, Run and Map

Three methods build the pipeline, and they differ in what happens after them:

  • Use adds a middleware that can call next. The pipeline continues after it.
  • Run adds a terminal middleware. It has no next; whatever it writes is the end of the line. Anything added after Run is never reached.
  • Map and MapWhen branch the pipeline. Requests whose path (or condition) matches go into a separate sub-pipeline; others continue on the main one.
C# Use, Map and Run together

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.

Two things to notice. First, inside the /admin branch the path is /users: Map strips the matched prefix (and moves it to PathBase). Second, all three lines report main saw it. Map is itself a middleware sitting in the chain, so everything added before it (here the header-setting Use) runs for every request. What the branch changes is what happens after that point: matching requests go into the sub-pipeline and never rejoin the main one, so the final Run is skipped for /admin and ?debug=1.

In everyday minimal-API code you rarely call Map for branching. Endpoint routing (MapGet, MapGroup) does the same job with better tooling. Map, MapWhen and UseWhen matter when you want a whole sub-pipeline, for example a different error handler for /api than for the rest of the site.

Order is the whole point

Middleware runs in the order you add it, and many components only work correctly in a specific position. A typical production pipeline looks like this (names are the real built-in methods):

C#
// Read-only: the usual order in Program.cs of a web app
app.UseExceptionHandler("/error");   // outermost: catches everything below
app.UseHsts();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseCors();
app.UseAuthentication();             // who are you?
app.UseAuthorization();              // are you allowed?
app.UseRateLimiter();
app.MapControllers();                // endpoints

The rules behind it are simple:

  • Exception handling goes first (outermost), so it can catch exceptions from everything inside it.
  • Authentication before authorization, and both before the endpoints that need them (see Authentication and Authorization).
  • Cheap rejections early. Static files and redirects before expensive work.
  • Anything that writes the response body should come after components that need to set headers, because headers cannot change once the body starts.

With WebApplication many of these calls are added for you automatically (routing and endpoint execution), which is why a minimal program works without them. You add them explicitly when you need to control the position.

Short-circuiting

A middleware may decide not to call next. That is called short-circuiting, and it is how many features work: a rate limiter that answers 429, an API-key check that answers 401, a cache that answers from memory, a health endpoint that answers 200 without touching the rest of the application.

C# A short-circuiting API key check

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 first middleware answers /health itself; the second blocks everything else without the key; only a request that passes both reaches the endpoint. Notice that setting StatusCode must happen before you write to the body. Once the first bytes of the response are sent, the status line and headers are gone for good. You can check context.Response.HasStarted to find out.

Middleware as a class

Lambdas are fine for quick things. For anything you want to reuse, test or inject services into, write a class. By convention the class has a constructor that takes RequestDelegate next (plus services that live for the whole application) and a method InvokeAsync(HttpContext context) (plus per-request services as extra parameters).

C#
public sealed class RequestCounterMiddleware
{
    private readonly RequestDelegate _next;

    public RequestCounterMiddleware(RequestDelegate next) => _next = next;

    public async Task InvokeAsync(HttpContext context, ICounter counter)
    {
        int number = counter.Next();
        context.Response.Headers["X-Request-Number"] = number.ToString();
        await _next(context);
    }
}

You register the class with app.UseMiddleware<RequestCounterMiddleware>(). Services are resolved by the dependency injection container: constructor parameters must be singletons (the middleware instance lives as long as the app), while InvokeAsync parameters can use any lifetime, including scoped. Injecting a scoped service into the constructor is a classic bug, because the middleware would capture one scope forever. See Dependency Injection for lifetimes.

An alternative is to implement the IMiddleware interface, which is created from the container per request (so it may have scoped dependencies in the constructor) and must be registered as a service. The convention-based style is more common and slightly faster.

C# A middleware class with injected services

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.

It is common to hide UseMiddleware<T>() behind an extension method such as app.UseRequestCounter(), which is how the built-in UseAuthentication() and friends are written (see extension methods).

Handling exceptions in one place

Because the pipeline is a chain of calls, a try/catch in an outer middleware catches exceptions thrown by everything inside it. That makes error handling a perfect middleware job: endpoints can simply throw, and one component turns the exception into a response.

C# An exception handling middleware

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.

Note that the 500 response says nothing about secret internals. Never send exception messages or stack traces to clients in production; they leak implementation details. Log them on the server instead.

ASP.NET Core ships its own version of this: app.UseExceptionHandler(...), which re-runs the request against an error path or handler, and app.UseDeveloperExceptionPage() for development only. In .NET 8 and later you can also register one or more IExceptionHandler services (builder.Services.AddExceptionHandler<MyHandler>()) that get a chance to translate each exception, plus builder.Services.AddProblemDetails() for standard error bodies. The next lesson, Validation and Problem Details, builds on that.

Request logging middleware

Logging each request with its status and duration is another classic. Capture a Stopwatch before next, read the status code after it. The example below stores log lines in a list instead of printing them as they happen, so the output is predictable (durations are not shown, because timings vary from run to run).

C# Logging method, path and status

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 finally block guarantees the line is written even when something throws. A real application would use ILogger<T> (see Logging), and ASP.NET Core already has app.UseHttpLogging() and built-in request logs at the Information level, so write your own only when you need something custom.

Endpoint filters

Middleware sees every request. Sometimes you want behavior for one endpoint or one group of endpoints, and you want access to the endpoint's typed arguments rather than a raw HttpContext. Minimal APIs provide endpoint filters for that. A filter wraps the endpoint handler: it receives an EndpointFilterInvocationContext (with the bound arguments) and a next delegate, and returns the result.

C# Endpoint filters on a route group

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 first filter returns a 400 without ever running the handler (a short-circuit, just like in middleware). The group filter post-processes the handler's result. Filters run in the order they are added, outermost first.

Middleware or filter?

Question Use middleware Use an endpoint filter
Applies to every request, including static files and non-endpoints? Yes No
Needs the typed handler arguments or the endpoint result? No Yes
Examples exception handling, HTTPS redirect, CORS, authentication, compression validating one DTO, caching one result, logging arguments

A good rule: start with middleware for anything about the HTTP request as a whole; use filters when the logic is about a particular endpoint's inputs and outputs.

Common mistakes

  • Wrong order. Putting UseAuthorization() before UseAuthentication(), or an exception handler after the middleware that throws, silently breaks the feature.
  • Forgetting await next(context) or calling next twice. The second call runs the rest of the pipeline again.
  • Writing the body, then changing the status. After HasStarted is true, you cannot change headers.
  • Capturing scoped services in a middleware constructor. Take them as InvokeAsync parameters instead.
  • Doing slow work on the pipeline without async. Blocking calls (.Result, Thread.Sleep) starve the thread pool; see async pitfalls.
  • Swallowing exceptions without logging them.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In what order does the code before and after await next(context) run for two middleware A then B?

    The pipeline is a chain of nested calls. The request goes in through A then B, and the response unwinds in reverse order, so B's after-code runs before A's.
  2. 2. What does a middleware added with app.Run(...) do?

    Run adds a terminal middleware. It cannot call next, so anything added after it is unreachable.
  3. 3. Where should an exception handling middleware be placed?

    A try/catch only catches what happens inside it. The exception handler must wrap the rest of the pipeline, so it goes first.
  4. 4. Which parameters can a convention-based middleware take in InvokeAsync but should NOT take in its constructor?

    The middleware instance is created once and lives for the whole application, so a scoped service in the constructor would be captured forever. Per-request services belong in InvokeAsync.
  5. 5. When is an endpoint filter a better fit than middleware?

    Endpoint filters see the bound arguments and the handler's result and apply to selected endpoints; middleware sees raw HttpContext for every request.

Summary

  • Middleware forms a pipeline: each component gets HttpContext and next, can act before and after next, and may short-circuit by not calling it.
  • Use continues the pipeline, Run terminates it, Map/MapWhen branch it into a separate sub-pipeline.
  • Order matters: exception handling first, then HTTPS/static files, routing, CORS, authentication, authorization, endpoints.
  • Write reusable middleware as a class with InvokeAsync; put scoped services in InvokeAsync parameters, not the constructor.
  • Centralize error handling and request logging in middleware; never leak exception details to clients.
  • Endpoint filters wrap individual endpoints or groups and see typed arguments and results.

Next: Validation and Problem Details