ASP.NET Core 2.0 Middleware

Problem

Create a Hello World using ASP.NET Core Middleware.

Solution

Starting from the Empty Project from a previous post, amend the Configure() method in Startup.cs as below:

It is a good practice to use extension methods on IApplicationBuilder to build the pipeline:

In the previous snippet we used IApplicationBuilder.Run() to configure middleware, another way to do this is IApplicationBuilder.Use():

It is a good practice to have middleware components defined in a separate class:

Discussion

Middleware is a component that intercepts HTTP request and response messages. We create a chain of these components to build a request pipeline for our application.

We setup this pipeline in Configure() method via its IApplicationBuilder parameter, that has following methods for this purpose:

  1. Run(): adds a middleware and ends the pipeline i.e. doesn’t call next middleware.
  2. Use(): adds a middleware, as a lambda or a dedicated class.
  3. Map(): adds middleware based on request paths

Run

It takes RequestDelegate delegate as a parameter, which when called has HttpContext as its parameter. It returns void because it short-circuits the request pipeline.

Use

It takes Func as a parameter i.e. takes in HttpContext and a pointer to next middleware, and returns nothing (Task). If the next middleware is not called, it short-circuits the request pipeline (same as Run).

UseMiddleware

When setting up middleware as a class, we use UseMiddleware to wire it up, providing our class as generic parameter.

The dedicated middleware class has two important pieces in it:

  1. Its constructor accepts RequestDelegate. This will be called to forward the request to next middleware.
  2. It has a method Invoke accepting HttpContext and returning a Task. This is called by the framework when calling the middleware.

Note: implementing middleware in a dedicated class and wiring up using UseMiddleware is the best/cleanest approach.

Extension Methods

Note the difference in extension methods, RunXXX doesn’t return a value I however UseXXX does (IApplicationBuilder). This is because Run() ends (short-circuits) the pipeline whereas Use() may be chained with other middleware.

Order

Middleware components are called in the order they appear in Configure() method i.e. the order in which their added to the pipeline. The response, on its way back to client, also passes through the same middleware pipeline.

Source Code

GitHub: https://github.com/TahirNaushad/Fiver.Asp.Middleware

Leave a Reply