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:
- HTTPS gate: "Use the secure door, please."
- Error gate: "If anything goes wrong inside, I will show a polite error page."
- Files gate: "Asking for
app.css? Here it is." The visitor goes no further. - 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. Callingnextpasses 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 withapp.Use...()and endpoints withapp.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:
| Line | What it does |
|---|---|
UseExceptionHandler | Catches errors and shows the /Error page |
UseHsts | Tells browsers to always use HTTPS for this site |
UseStatusCodePagesWithReExecute | Shows the /not-found page for "not found" answers |
UseHttpsRedirection | Sends http:// visitors to https:// |
UseAntiforgery | Protects forms from fake posts from other sites |
MapStaticAssets | Serves 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 thecontextandnext.app.Run(...)adds the last step. It gets only thecontext, 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:
| Middleware | Its job |
|---|---|
MapStaticAssets | Sends files from wwwroot (CSS, images, JavaScript) |
UseHttpsRedirection | Moves visitors from http:// to https:// |
UseExceptionHandler | Catches errors and shows a friendly error page |
UseStatusCodePagesWithReExecute | Shows 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.jsfile. app.MapStaticAssets()serves every file in thewwwrootfolder. 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 anhttp://request with status 307 and aLocationheader that points to thehttps://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.
Locationsays "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 afternext(). 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.
/boomthrows an error, but the user gets the friendly/Errorpage with status 500./missinghas no page, so the user gets the/not-foundpage with status 404.- Try removing
app.UseExceptionHandler("/Error");and click/boomagain: you get a bare 500 with no body.
Use, Run and Map
Three methods add steps to the pipeline:
| Method | What it adds | Calls next? |
|---|---|---|
app.Use(...) | Middleware that does something and passes the request on | Yes, 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 /path | Only inside the branch |
- A branch is like a side road. Requests for
/adminturn off into it. All others go straight on. - Inside the branch, the
/adminpart is taken off the path. So/admin/ordersis 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.
MapStaticAssetsandUseHttpsRedirectionshort-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). Bothnext()andnext(context)work, butnext(context)is a little faster. app.Loggerwrites to the log, which you see in the terminal wheredotnet runis running.
Middleware Classes
When the code grows, move it into a class. A middleware class has three parts:
- A constructor that receives
next, of typeRequestDelegate(a method that handles a request). - A method
InvokeAsync(HttpContext context)that does the work and callsnext. - 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.Incrementadds 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
| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
Forgetting await next() in app.Use | The next middleware runs by itself | Call await next() unless you mean to stop | The page never runs, and the user gets an empty answer |
UseExceptionHandler added late in the list | Order does not matter | Add it first, so it wraps everything | Errors before it are not caught |
Adding middleware after app.Run(...) | Every line runs | Keep app.Run(...) as the last step | The middleware after it never runs |
Writing to the response, then calling next() | Two answers can be joined | Either answer and return, or call next() | Mixed bodies or an error |
Mixing up app.Run(handler) and app.Run() | They do the same thing | Run(handler) is the last step; Run() starts the server | Code 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, afterbuilder.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,MapStaticAssetsand your pages. Usepasses the request on withnext().Runis the last step.Mapmakes 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 aRequestDelegateconstructor,InvokeAsync(HttpContext)andapp.UseMiddleware<T>().
Next: Authentication