Creating Custom ASP.NET Core Middleware

In this article, we are going to learn how to create a custom Middleware in ASP.NET CORE and register it in Startup class.
We are going to create an ASP.NET Core application with the name DemoWebApplication.

After creating Project Next, we are going to add a folder to this project with name CustomMiddleware after adding folder right click on CustomMiddleware folder and select Add inside that select NewItem.

A new dialog pop up in search box type middleware and select Middleware class we are going to name this middleware as FirstMiddleware and click on Add button.

After clicking on Add, New Middleware is added with class name FirstMiddleware along with Extension method used to attach the middleware to the HTTP request pipeline.

Below is the source code of Middleware class which is generated by using Scaffolding.

Code snippet

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;

namespace DemoWebApplication.CustomMiddleware
{
    // You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project
    public class FirstMiddleware
    {
        private readonly RequestDelegate _next;

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

        public Task Invoke(HttpContext httpContext)
        {

            return _next(httpContext);
        }
    }
    // Extension method used to add the middleware to the HTTP request pipeline.
    public static class FirstMiddlewareExtensions
    {
        public static IApplicationBuilder UseFirstMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<FirstMiddleware>();
        }
    }
}

All logic is to be written inside the Invoke method. We are going write a custom message to display in the browser for doing that we need to make FirstMiddleware Middleware async.
Below are changes we are going to make Middleware asynchronous.

Code snippet

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;

namespace DemoWebApplication.CustomMiddleware
{
    // You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project
    public class FirstMiddleware
    {
        private readonly RequestDelegate _next;

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

        // Change1 : Made Method async
        public async Task Invoke(HttpContext httpContext)
        {
            // Change2 : Writing Response
            await httpContext.Response.WriteAsync("Custom Middleware Executed");
            // Change3 : Removed return and added await 
            await _next(httpContext);
        }
    }

    // Extension method used to add the middleware to the HTTP request pipeline.
    public static class FirstMiddlewareExtensions
    {
        public static IApplicationBuilder UseFirstMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<FirstMiddleware>();
        }
    }
}

Now we have made small changes in middleware let’s Register this middleware in Http Request pipeline.

There are two ways to Register Middleware in the Configure method

  1. Without Extension
    app.UseMiddleware();
  2. With Extension
    app.UseFirstMiddleware();

If you see FirstMiddlewareExtensions method, then you will find it internally uses UseMiddleware to add Middleware to the HTTP pipeline.

Using the extension method code looks cleaner.

Code snippet

public static class FirstMiddlewareExtensions
{
     public static IApplicationBuilder UseFirstMiddleware(this IApplicationBuilder builder)
     {
         return builder.UseMiddleware<FirstMiddleware>();
     }
}

Code snippet After adding Middleware to the Http request pipeline

In the configure method we are going to register the middleware in the Http request pipeline.

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // Without Extension method if you want to Add
    // app.UseMiddleware<FirstMiddleware>();

    // Custom Middleware Added with Extension method
    app.UseFirstMiddleware();

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}

Now let’s run the application to test your First middleware.

Output

By Saineshwar Bageri

I am Microsoft MVP | C# Corner MVP | Code Project MVP | FULL STACK .NET Developer and working on .Net Web Technology (Asp.net, Asp.net Core,.Net Core, C#, Sqlserver, MVC, Windows, Console Application, javascript, jquery, json, ORM Dapper) and also a freelance developer.