A Professional ASP.NET Core - Middleware
Middleware is software that’s assembled into an app pipeline to handle requests and responses. Each component:
- Chooses whether to pass the request to the next component in the pipeline.
- Can perform work before and after the next component in the pipeline.
Request delegates are used to build the request pipeline. The request delegates handle each HTTP request.
Request delegates are configured using Run
, Map
, and Use
extension methods. An individual request delegate can be specified in-line as an anonymous method (called in-line middleware), or it can be defined in a reusable class. These reusable classes and in-line anonymous methods are middleware, also called middleware components. Each middleware component in the request pipeline is responsible for invoking the next component in the pipeline or short-circuiting the pipeline. When a middleware short-circuits, it’s called a terminal middleware because it prevents further middleware from processing the request.
Create a middleware pipeline with IApplicationBuilder
The ASP.NET Core request pipeline consists of a sequence of request delegates, called one after the other. The following diagram demonstrates the concept. The thread of execution follows the black arrows.
Each delegate can perform operations before and after the next delegate. Exception-handling delegates should be called early in the pipeline, so they can catch exceptions that occur in later stages of the pipeline.
The simplest possible ASP.NET Core app sets up a single request delegate that handles all requests. This case doesn’t include an actual request pipeline. Instead, a single anonymous function is called in response to every HTTP request.
1 |
|
Chain multiple request delegates together with Use
. The next parameter represents the next
delegate in the pipeline. You can short-circuit the pipeline by not calling the next parameter. You can typically perform actions both before and after the next delegate, as the following example demonstrates:
1 |
|
When a delegate doesn’t pass a request to the next
delegate, it’s called short-circuiting
the request pipeline. Short-circuiting is often desirable because it avoids unnecessary work. For example, Static File Middleware can act as a terminal middleware by processing a request for a static file and short-circuiting the rest of the pipeline. Middleware added to the pipeline before the middleware that terminates further processing still processes code after their next.Invoke
statements. However, see the following warning about attempting to write to a response that has already been sent.
Run
delegates don’t receive a next parameter. The first Run
delegate is always terminal and terminates the pipeline. Run is a convention. Some middleware components may expose Run[Middleware]
methods that run at the end of the pipeline:
Middleware order
The following diagram shows the complete request processing pipeline for ASP.NET Core MVC and Razor Pages apps. You can see how, in a typical app, existing middlewares are ordered and where custom middlewares are added. You have full control over how to reorder existing middlewares or inject new custom middlewares as necessary for your scenarios.
The Endpoint
middleware in the preceding diagram executes the filter pipeline for the corresponding app type—MVC or Razor Pages.
Methods at a glance
Request delegates are configured using various extension methods as following:
Run
Terminates chain. No other middleware method will run after this. Should be placed at the end of any pipeline.
1 |
|
UseWhen
Performs action before and after next delegate if condition is met.
1 |
|
Use
Performs action before and after next delegate.
1 |
|
MapWhen
Enables branching pipeline. Runs specified middleware if condition is met.
1 |
|
Map
Similar to MapWhen
. Runs middleware if path
requested by user equals path provided in parameter.
1 |
|
Common middlewares (in order)
The following is a list of common middlewares in order:
1 |
|
Componentising custom middleware
In some scenarios you might want to write a custom middleware.
Write below classes:
1 |
|
The middleware class must include:
- A public constructor with a parameter of type
RequestDelegate
. - A public method named
Invoke
orInvokeAsync
. This method must:- Return a
Task
. - Accept a first parameter of type
HttpContext
.
- Return a
Additional parameters for the constructor and Invoke
or InvokeAsync
are populated by dependency injection (DI).
Now, use it as following:
1 |
|
Adding custom options to middleware
Writing a custom middleware is great but you will come to a point where it needs to be made configurable.
Let’s define a configuration options class which defines some options which the middleware can use.
1 |
|
Write extension methods to get options with Action<CustomMiddlewareOptions>
as following:
1 |
|
The middleware now can be added into the pipeline and be setup using a lambda expression. It can take the Options in through constructor through the DI mechanism. It comes from the IOptions<T>
functionality.
1 |
|
Register and config it as below:
1 |
|
Multiple configuration setup
The other option is the multiple configuration setup option where you want to be able to use the same type of middleware more than once in your application pipeline but want to specify configuration per usage. For this option you specify that you require a configuration option instance directly and it’s not hidden behind IOptions<>
.
1 |
|
Adding this version into the middleware pipeline is much straight forward however using an extension method makes it cleaner from a consumers point of view.
1 |
|
Passing in the options instance into the UseMiddleware method call allows for the DI system inject it into the middleware constructor directly.
Using this extension method we can then add in multiple instances into the pipeline with different configuration options specified.
1 |
|
Reference(s)
Most of the information in this article has gathered from various references.
- https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware
- https://adamstorr.azurewebsites.net/blog/aspnetcore-exploring-custom-middleware
- https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/write
- https://www.devtrends.co.uk/blog/conditional-middleware-based-on-request-in-asp.net-core
- https://riptutorial.com/asp-net-core/example/20718/run--map--use