Custom Middleware in ASP.NET Core

Custom Middleware in ASP.NET Core

In this article, I am going to discuss How to Create, Register, and use Custom Middleware Components in ASP.NET Core Application. Please read our previous article where we discussed Run. Next, Map, and Use Extension methods in ASP.NET Core with examples. In fact, we are also going to work with the same example that we created in our Run, Next, and Use Extension Methods article.

Creating Custom Middleware in ASP.NET Core

While working with the real-time applications in ASP.NET Core Web API, it is a common requirement to create Custom Middleware Components. So, let us add a new class file to our project. It is this class file that is going to contain the logic. So, right-click on the project name and then select add => class as shown in the below image.

Creating Custom Middleware in ASP.NET Core

From the next add new class screen, select the class template and provide the class name as MyCustomMiddleware1 and then click on the Add button as shown in the below image.

How to Create, Register, and use Custom Middleware Components in ASP.NET Core

In order to make a class a Middleware component, the class needs to be inherited from the IMiddleware interface. Further IMiddleware interface belongs to Microsoft.AspNetCore.Http namespace. And we need to implement the InvokeAsync method. And you need to write your logic within the InvokeAsync method. So, modify the MyCustomMiddleware1 class as shown below.

using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
namespace MiddlewareInASPNETCore
{
    public class MyCustomMiddleware1 : IMiddleware
    {
        public async Task InvokeAsync(HttpContext context, RequestDelegate next)
        {
            await context.Response.WriteAsync("Custom Middleware Incoming Request \n");
            await next(context);
            await context.Response.WriteAsync("Custom Middleware Outgoing Response \n");
        }
    }
}

Note: While calling the next method from any custom middleware components, we need to pass the context object and that you can see in the above code.

Our Custom Middleware component is ready. Now we need to use it in our HTTP Request Processing pipeline. Now it is a two-step process to use this custom middleware component.

Step1: Inject the service to the built-in dependency injection container

Remember if you want to use any custom service, before using it, you must inject the service into the built-in IoC Container. You can inject the service using the ConfigureService method of the Startup class as services.AddTransient<MyCustomMiddleware1>();. We will discuss AddTransient and its working in detail while we discuss dependency injection. For now, just we this method to configure the custom services. So, modify the ConfigureService method of the Startup class as shown below.

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    services.AddTransient<MyCustomMiddleware1>();
}
Step2: Registering the Custom Middleware in the HTTP Request Processing Pipeline

Once you configure the service to the built-in IoC Container, then you can use the Middleware. As we already discussed we can configure the Middleware to the Request Processing Pipeline using the Configure method of the Startup class. To configure the custom Middleware we need to use the UseMiddleware Extension method as app.UseMiddleware<MyCustomMiddleware1>(); So, modify the Configure method of the Startup class as shown below.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.Use(async (context, next) =>
    {
        await context.Response.WriteAsync("Use Middleware Incoming Request \n");
        await next();
        await context.Response.WriteAsync("Use Middleware Outgoing Response \n");
    });

    app.UseMiddleware<MyCustomMiddleware1>();

    app.Run(async context => {
        await context.Response.WriteAsync("Run Middleware Component\n");
    });
}

Now save the changes and run the application and you should get the following response in the browser as expected.

Custom Middleware Component in ASP.NET Core

Points to Remember while working with ASP.NET Core Middleware:
  1. The ASP.NET Core Request Processing Pipeline consists of a sequence of middleware components (custom plus built-in) that are going to be called one after the other. If we want to call the next middleware components then we need to use the next method.
  2. Each middleware component in ASP.NET Core Application can perform some operations before and after calling the next component using the next method. A middleware component in ASP.NET Core Application can also decide not to call the next middleware component which is called short-circuiting the request pipeline.
  3. The ASP.NET Core middleware component can access both the incoming request and the outgoing response.
  4. The Run method in ASP.NET Core is the terminating Middleware Component which means it is not possible to call the next middleware component.
  5. The order in which the middleware components are registered in the Configure method defines the order in which these middleware components are going to be invoked on requests and the reverse order for the response. So, the order is critical for defining the security, performance, and functionality of the application.

In the next article, I am going to discuss Routing in ASP.NET Core Web API Application. Here, in this article, I try to explain How to Create, Register and Use Custom Middleware Component in ASP.NET Core Application. And I hope you enjoy this Custom Middleware Component in the ASP.NET Core Application article.

Leave a Reply

Your email address will not be published.