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
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.
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.
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:
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:
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.
Endpoint middleware in the preceding diagram executes the filter pipeline for the corresponding app type—MVC or Razor Pages.
Request delegates are configured using various extension methods as following:
Terminates chain. No other middleware method will run after this. Should be placed at the end of any pipeline.
Performs action before and after next delegate if condition is met.
Performs action before and after next delegate.
Enables branching pipeline. Runs specified middleware if condition is met.
MapWhen. Runs middleware if
path requested by user equals path provided in parameter.
The following is a list of common middlewares in order:
In some scenarios you might want to write a custom middleware.
Write below classes:
The middleware class must include:
- A public constructor with a parameter of type
- A public method named
InvokeAsync. This method must:
- Return a
- Accept a first parameter of type
- Return a
Additional parameters for the constructor and
InvokeAsync are populated by dependency injection (DI).
Now, use it as following:
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.
Write extension methods to get options with
Action<CustomMiddlewareOptions> as following:
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
Register and config it as below:
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
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.
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.
Most of the information in this article has gathered from various references.