How to build custom middleware in ASP.NET Core

Take advantage of ASP.NET Core middleware to customize your application’s handling of HTTP requests and responses.

How to build custom middleware in ASP.NET Core
Thinkstock

ASP.NET Core is an open source, cross-platform, lean, and modular framework for building high-performance web applications. It is also extensible. When building an ASP.NET Core application, you can draw on various middleware components to customize the handling of requests and responses, and even inspect, route, or modify the request and response messages that flow through the pipeline. This article presents a discussion of ASP.NET Core middleware and how it can be used, with relevant code examples in C#.

Usually, you have a chain of middleware components in the application pipeline in ASP.NET Core. The ASP.NET Core request pipeline contains a series of request delegates that are invoked one after the other. Incoming requests flow through each of the middleware components in the pipeline, and each of these components can either process the request or pass the request to the next component in the pipeline.

Configuring the ASP.NET Core middleware pipeline

The middleware pipeline is configured using the Configure method in the Startup.cs file. This is exactly where you can chain together your ASP.NET Core pipeline. The Configure method is automatically called by the ASP.NET runtime. Here is a quick look at this method.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IdentityDbContext dbContext)
    {
        app.UseDeveloperExceptionPage();           
        app.UseStaticFiles();          
        app.UseMvcWithDefaultRoute();
    }

The above code snippet illustrates how you can add MVC to the ASP.NET Core request execution pipeline. In the next section, we will build a custom middleware component for ASP.NET Core.

Create an ASP.NET Core project in Visual Studio

Assuming that you have .NET Core installed in your system (preferably .NET Core 2), you can follow these steps to create a new ASP.NET Core project in Visual Studio 2017 or Visual Studio 2015.

  1. Open Visual Studio
  2. Click File -> New -> Project
  3. In the New Project dialog window, select the ASP.NET Core Web Application project template
  4. Specify the name and location for your project and click OK to save
  5. In the next screen, select Web API from the list of templates, unselect authentication and Docker support (we don’t need either of these for now), and save the project

And that’s all you need to do to create an ASP.NET Core web application that leverages Web API. We will now build a custom middleware component that checks if the authentication key passed in the request is valid. If the authentication key is not valid, the request will be rejected with an appropriate message.

Create a custom ASP.NET Core middleware component

You have an extension method in IApplicationBuilder that you can take advantage of to build your own middleware in ASP.NET Core. Note that it is always a good practice to write your middleware component in a separate class or a separate project so that you can update the middleware if need be, without having to change your service layer.

There are various ways to build a custom middleware component—I will demonstrate the simplest way. Right-click on the project in the Solution Explorer window and create a new .cs file named MyCustomMiddleware. At first glance, this class will look like this.

public class MyCustomMiddleware
    {
        //This is our custom middleware
    }

Note that your custom middleware should have a constructor with a parameter of type RequestDelegate. A RequestDelegate is a just another delegate that accepts an HttpContext and returns a Task. Here is how the modified version of our custom middleware should look.

public class MyCustomMiddleware
    {
        private readonly RequestDelegate _next;
        public MyCustomMiddleware(RequestDelegate next)
        {
            _next = next;
        }
    }

Invoke your custom ASP.NET Core middleware

Your middleware should also have a method that will be called when the middleware is executed. This is the Invoke method as shown in the code listing below. Note that this method has been named Invoke in this example only by convention. It is here that you can write your code to inspect or modify the requests and responses.

public class MyCustomMiddleware
    {
        private readonly RequestDelegate _next;
        public MyCustomMiddleware(RequestDelegate next)
        {
            _next = next;
        }
        public async Task Invoke(HttpContext httpContext)
        {
            if (!httpContext.Request.Headers.Keys.
              Contains(“Authentication-Key”))
            {
                httpContext.Response.StatusCode = 400;             
                await httpContext.Response.WriteAsync
                   (“Authentication key is missing...”);
                return;
            }
            else
            {
               //Write code here to validate the authentication key.
            }
            await _next.Invoke(httpContext);
        }
    }

Refer to the code listing given above. If the request header does not contain a valid authentication key, then an appropriate message will be returned as a response when you run your Web API. (Note that ”Authentication-Key” is a string that would be compared against a list of valid keys.)

Create an extension method for ASP.NET Core middleware

Let’s now create an extension method for our custom middleware. The purpose of the extension method is to make it easier to register the middleware to the pipeline. The ASP.NET team recommends exposing an IApplicationBuilder extension method that can be called from the Configure method. Here’s how you can build an extension method that takes advantage of IApplicationBuilder.

public static class MyCustomMiddlewareExtensions
    {
        public static IApplicationBuilder UseMyCustomMiddleware
         (this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<MyCustomMiddleware>();
        }
    }

Lastly, you should configure your custom middleware in the Configure method as shown below. Then you can use your extension method — e.g. UseMyCustomMiddleware()— as illustrated in the code snippet given below.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseMyCustomMiddleware();
        }

Middleware in ASP.NET Core allows us to create very flexible web applications. Our authentication key example is just one of many ways we might take advantage of middleware. You can learn more about ASP.NET Core middleware from this article in the ASP.NET Core documentation.

Copyright © 2018 IDG Communications, Inc.