Middleware Pipeline

By Syncfusion®, Inc. · Last updated

How every request passes through middleware: the ASP.NET Core request pipeline, Program.cs setup, execution order, built-in middleware (static files, HTTPS redirection, exception handling, status code pages), Use, Run and Map, short-circuiting, and inline and class middleware.

What you will learn

  • Explain how a request travels through the middleware pipeline
  • Configure and order middleware in Program.cs
  • Use Use, Run and Map, and short-circuit the pipeline
  • Write custom middleware inline and as a class

Middleware Introduction

  • You know from API Integration that the browser sends a request and the server sends back a response.
  • Before your page sees a request, small pieces of code on the server look at it first. Each piece is called middleware.
  • A middleware can check the request, change it, answer it by itself, or pass it on to the next middleware.
  • On the way back, the same middleware can look at the response too.

Real-World Example:

Think of the Tea Shop's web server as a building with a few gates. A visitor (the request) walks through them in order:

  1. HTTPS gate: "Use the secure door, please."
  2. Error gate: "If anything goes wrong inside, I will show a polite error page."
  3. Files gate: "Asking for app.css? Here it is." The visitor goes no further.
  4. Your page: everyone else reaches the Blazor page that makes the answer.

Animation: a request leaves the browser and passes three middleware boxes, HTTPS, Errors and Static files, to reach the endpoint, your page. The response then travels back through the same three boxes to the browser.

Browser

HTTPS

Errors

Static files

Endpoint your page

request goes in response comes back

Every request passes the middleware in order. The response comes back the same way.

ASP.NET Core Request Pipeline

  • Blazor apps run on ASP.NET Core, the .NET framework for web servers.
  • The middleware, joined one after another, form the request pipeline, like water flowing through a pipe.
  • At the end of the pipe is the endpoint: the code that makes the real answer, such as a Blazor page or an API action.
  • Each middleware gets a next: a way to call the middleware after it. Calling next passes the request on.
  • Every request gets a HttpContext: one object with the request (path, method) and the response (status code, body). All middleware share it.

In Blazor, the pipeline runs for each HTTP request: loading a page, a CSS file or an API call. With interactive rendering, button clicks travel over the open connection (SignalR) or run in the browser, so they do not pass through the middleware again.

The code boxes cannot run a real web server. So FakePipeline.cs gives them a small pretend pipeline with the same method names as the real one: Use, Run, Map, UseMiddleware. Its context is called FakeContext instead of HttpContext.

Configuring Middleware in Program.cs

  • You set up the pipeline in Program.cs, the file that starts your app.
  • It has two halves. Before builder.Build(), you register services (see Dependency Injection). After it, you add middleware with app.Use...() and endpoints with app.Map...().
  • Each app.Use... line adds one middleware. The order of the lines is the order of the pipeline.

This is the Program.cs of a new Blazor Web App:

LineWhat it does
UseExceptionHandlerCatches errors and shows the /Error page
UseHstsTells browsers to always use HTTPS for this site
UseStatusCodePagesWithReExecuteShows the /not-found page for "not found" answers
UseHttpsRedirectionSends http:// visitors to https://
UseAntiforgeryProtects forms from fake posts from other sites
MapStaticAssetsServes files from wwwroot, like app.css
MapRazorComponents<App>Your Blazor pages: the main endpoint
app.Run()Starts the server. Always the last line.

You meet the first four again in Built-in Middleware below.

Your First Pipeline

  • app.Use(...) adds middleware. It gets the context and next.
  • app.Run(...) adds the last step. It gets only the context, because nothing comes after it.
  • context.Response.WriteAsync("...") writes text into the response body.

In the below example, a logging middleware writes a line before and after next(), and app.Run answers. Click Send /.

  • Code before await next() runs on the way in. Code after it runs on the way out.
  • app.Run(...) with a handler adds an endpoint. app.Run() with nothing starts the server. Same name, two different jobs.

Middleware Execution Order

  • Middleware run in the order you add them on the way in.
  • On the way out, they run in reverse order, like taking off layers of clothes.
  • So the first middleware sees the request first and the response last. That is why the error catcher comes first: it wraps everything after it.

Animation: three nested boxes, Middleware A outside, B inside it, C inside B, and the endpoint in the middle. A dot goes down through A, B and C on the left (before next), crosses the endpoint, and comes back up through C, B and A on the right (after next).

Middleware A

Middleware B

Middleware C

Endpoint in: A, B, C out: C, B, A

Each middleware wraps the ones after it. In: A, B, C. Out: C, B, A.

In the below example, three middleware write a line before and after next(). Click Send / and read the order. Then move the C block above A and run it again.

Order is a common source of bugs. For example, if the error catcher is added after the middleware that fails, it never sees the error. Keep the order of the template.

Built-in Middleware

ASP.NET Core comes with ready-made middleware. You only add one line for each. These are the ones in every Blazor app:

MiddlewareIts job
MapStaticAssetsSends files from wwwroot (CSS, images, JavaScript)
UseHttpsRedirectionMoves visitors from http:// to https://
UseExceptionHandlerCatches errors and shows a friendly error page
UseStatusCodePagesWithReExecuteShows a page for answers like 404 Not Found

Static Files (MapStaticAssets)

  • A static file is a file sent exactly as it is, with no code running: app.css, favicon.png, a .js file.
  • app.MapStaticAssets() serves every file in the wwwroot folder. For /app.css, it sends the file and the request goes no further.
  • It also helps speed: files are compressed (made smaller) and the browser is told how long it may keep them.

HTTPS Redirection (UseHttpsRedirection)

  • HTTPS is the secure version of HTTP. The data is encrypted: scrambled, so others on the network cannot read it.
  • app.UseHttpsRedirection() answers an http:// request with status 307 and a Location header that points to the https:// address. The browser then asks again, securely.
  • A header is a small extra line of information on a request or response, like a label on a parcel. Location says "go here instead".

Exception Handling (UseExceptionHandler)

  • An exception is an error that stops the code, like throw new Exception(...).
  • app.UseExceptionHandler("/Error") catches exceptions from everything after it. It then re-executes the request: it sends it through the pipeline again with the path /Error, so the user sees your friendly error page with status 500.
  • The template adds it only outside Development. While you develop, you see the full error details instead.

Status Code Pages (UseStatusCodePagesWithReExecute)

  • Some answers have a status code like 404 but no body, so the browser shows an empty page.
  • app.UseStatusCodePagesWithReExecute("/not-found") runs after next(). If the status is 400 or higher and nothing was written, it re-executes the request with the path /not-found. The status code stays 404.

In the below example, the four built-in middleware are in a pretend pipeline. The app.Run step plays the part of your Blazor pages. Click each button and compare the status and body.

  • /boom throws an error, but the user gets the friendly /Error page with status 500.
  • /missing has no page, so the user gets the /not-found page with status 404.
  • Try removing app.UseExceptionHandler("/Error"); and click /boom again: you get a bare 500 with no body.

Use, Run and Map

Three methods add steps to the pipeline:

MethodWhat it addsCalls next?
app.Use(...)Middleware that does something and passes the request onYes, usually
app.Run(...)The last step. It always answers.No, there is no next
app.Map("/path", ...)A branch: a separate small pipeline for paths that start with /pathOnly inside the branch
  • A branch is like a side road. Requests for /admin turn off into it. All others go straight on.
  • Inside the branch, the /admin part is taken off the path. So /admin/orders is seen as /orders.

A main road of middleware. At a fork labelled Map /admin, requests that start with /admin turn into a side branch with its own Run step, Admin area. All other requests go straight on to the main Run step, Main shop.

Request

Use logger

Map /admin?

Run Main shop

Run (branch) Admin area

other paths /admin...

Map sends matching requests down their own branch.

In the below example, Map("/admin", ...) adds a branch. Click each button and look at the body and the path the branch sees.

Anything added after app.Run(...) never runs, because Run does not call next. Keep Run at the end.

Short-Circuiting the Pipeline

  • Short-circuiting means a middleware answers by itself and does not call next(). The rest of the pipeline never runs.
  • It is useful when the answer is already clear: a static file was found, the user is not allowed in, or the shop is closed for maintenance.
  • It also saves work, because the page code does not run at all.

Animation: a request passes the first middleware, reaches the second middleware, Closed?, and turns back at once with 503. The third middleware and the endpoint are greyed out because they never run.

Browser

Logger

Closed? answers 503

More...

Endpoint

never reached

The second middleware answers by itself. Nothing after it runs.

In the below example, a middleware checks a closed switch. When it is on, the middleware answers 503 Service Unavailable and returns without calling next(). Tick the box, click Send / and look at the log.

  • With the box ticked, the log has no "Endpoint" line. The logger still writes its "out" line, because the response passes back through it.
  • MapStaticAssets and UseHttpsRedirection short-circuit in the same way.

Creating Custom Middleware

You can write your own middleware in two ways: inline, as a lambda inside Program.cs, or as a class in its own file.

Inline Middleware

  • Inline means the code is written right where it is used, as a lambda: a small unnamed method, (context, next) => { ... }.
  • It is good for short jobs. All the app.Use(...) examples above were inline.

This is how a real inline middleware looks in Program.cs. It measures how long each request takes:

  • In real code, pass the context on with next(context). Both next() and next(context) work, but next(context) is a little faster.
  • app.Logger writes to the log, which you see in the terminal where dotnet run is running.

Middleware Classes

When the code grows, move it into a class. A middleware class has three parts:

  1. A constructor that receives next, of type RequestDelegate (a method that handles a request).
  2. A method InvokeAsync(HttpContext context) that does the work and calls next.
  3. One line in Program.cs: app.UseMiddleware<T>().
  • The class is created once, when the app starts. So do not keep per-request data in fields.
  • Interlocked.Increment adds 1 safely, even when many requests arrive at the same moment.
  • The header name starts with X-: a common way to mark your own, non-standard headers.

In the below example, the same class uses FakeRequestDelegate and FakeContext, so it can run here. Click Send / a few times and watch the request ID grow.

Common mistakes

MistakeWrong ideaCorrect ideaWhat goes wrong
Forgetting await next() in app.UseThe next middleware runs by itselfCall await next() unless you mean to stopThe page never runs, and the user gets an empty answer
UseExceptionHandler added late in the listOrder does not matterAdd it first, so it wraps everythingErrors before it are not caught
Adding middleware after app.Run(...)Every line runsKeep app.Run(...) as the last stepThe middleware after it never runs
Writing to the response, then calling next()Two answers can be joinedEither answer and return, or call next()Mixed bodies or an error
Mixing up app.Run(handler) and app.Run()They do the same thingRun(handler) is the last step; Run() starts the serverCode that never runs, or an app that does not start

Check Yourself

Exercises

What to Remember

  • Middleware are small pieces of code that every request passes through. Together they form the request pipeline, which ends at an endpoint such as your Blazor page.
  • Set them up in Program.cs, after builder.Build(). The order of the lines is the order they run in. On the way out, the order is reversed.
  • Built-in: UseExceptionHandler (first), UseStatusCodePagesWithReExecute, UseHttpsRedirection, UseAntiforgery, MapStaticAssets and your pages.
  • Use passes the request on with next(). Run is the last step. Map makes a branch for one path.
  • Not calling next() short-circuits the pipeline: the middleware answers by itself.
  • Write custom middleware inline with app.Use, or as a class with a RequestDelegate constructor, InvokeAsync(HttpContext) and app.UseMiddleware<T>().

Next: Authentication