Custom .Net Core middleware

Share this post

What is Middleware?

Middleware is one or more software components, usually small, each encapsulated in a class, that are assembled into an application pipeline to handle requests and responses.

Each middleware component can:

  • Be executed before and after the next component in the pipeline.
  • Pass the request to next component in the pipeline, or terminate (short circuit) the pipeline.

The application pipeline is built using Request delegates (RequestDelegate) that are used to handle the incoming requests to the application.

Custom .Net Core middleware

Middleware setup

The middleware components are added to the application pipeline at the Configure method in the Startup class, using one more of the following extension methods:

  • Use
  • Map
  • Run

The following code snippet shows how to add two middleware components to an application pipeline with Use extension method:

public void Configure(IApplicationBuilder app) {
 app.UseHsts();
 app.UseHttpsRedirection();
}

Creating custom middleware

Creating a custom middleware in .Net Core is easy and requires only a few steps:

  • Creating the middleware class.
  • Creating the middleware extension class.
  • Adding the middleware to the application pipeline.

In short, I like to remember it as CEMPClass, Extension Methods and Application Pipeline.

Middleware class

We start by creating the middleware class which is a standard C# class that has a constructor with at least one parameter of type RequestDelegate and a InvokeAsync method.

public class ConsoleLoggingMiddleware
{
    private readonly RequestDelegate _next;

    public ConsoleLoggingMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        // Do some logic here

        // Call the next delegate/middleware in the pipeline
        await _next(context);
    }
}

The class can implement an IMiddleware interface, however, it is not required.

Extension method

Once we created the class, we create an extension method for it, in order to be able to add it to the application pipeline. The extension method will expose the middleware component through the IApplicationBuilder class.

public static class ConsoleLoggingMiddlewareExtensions
{
    public static IApplicationBuilder UseConsoleLoggingMiddleware(
        this IApplicationBuilder builder)
    {
        return builder.UseMiddleware();
    }
}

Application pipeline

Finally, using the extension method we just created, we add the middleware to the application pipeline:

public void Configure(IApplicationBuilder app)
{
    app.UseConsoleLoggingMiddleware();

    app.Run(async (context) =>
    {

    });

}

And that’s it, the newly created middleware is complete.

Note: Middleware should follow the Explicit Dependencies Principle by exposing it’s dependencies in it constructor.