Skip to content

Custom Middleware in ASP.NET Core MVC

Middleware is a piece of code used in the application pipeline to process incoming requests and their responses. Some middleware components are built into .NET Core, and we can also create custom middleware based on our requirements. Middleware is usually written as a class and registered through an extension method. Request delegates are used to build the request pipeline.

Problem definition: When a user requests the URL "/Home/Index", custom middleware should redirect them to the "/Home/CustomError" page instead.

In the image below you can see the URL, in which Home is the controller and Index is the action method. When we open this URL, it shows the Index page.

Browser opening the Home/Index URL before the custom middleware is added

After adding the middleware, opening the URL above redirects to the Home/CustomError page.

Custom middleware redirecting the request to the Home/CustomError page

Create a class named CheckUrlValidations with a constructor that stores the RequestDelegate. Write the InvokeAsync method with the URL-checking logic, then create an extension method UseCheckUrlValidations, as shown in the image and code below.

Custom middleware class with InvokeAsync and the UseCheckUrlValidations extension method
public class CheckUrlValidations

   {

       public readonly RequestDelegate RequestDelegate;

       public CheckUrlValidations(RequestDelegate requestDelegate)

       {

           RequestDelegate = requestDelegate;

       }

       public async Task InvokeAsync(HttpContext context)

       {

           var cultureQuery = context.Request.Path.Equals("/Home/Index");

           if(cultureQuery)

           {

               context.Response.Redirect("/Home/CustomError");

           }

           await RequestDelegate(context);

       }

   }

   public static class CheckUrlValidationsExtensions

   {

       public static IApplicationBuilder UseCheckUrlValidations(this IApplicationBuilder builder)

       {

           return builder.UseMiddleware<CheckUrlValidations>();

       }

   }

Now use this custom middleware in the Program.cs file, as shown in the image and code below.

Registering the custom middleware with app.UseCheckUrlValidations() in Program.cs
using MiddileWareExample.Models;

var builder = WebApplication.CreateBuilder(args);



// Add services to the container.

builder.Services.AddControllersWithViews();



var app = builder.Build();



// Configure the HTTP request pipeline.

if (!app.Environment.IsDevelopment())

{

    app.UseExceptionHandler("/Home/Error");

}

app.UseStaticFiles();



app.UseRouting();



app.UseAuthorization();

app.UseCheckUrlValidations();

app.MapControllerRoute(

    name: "default",

    pattern: "{controller=Home}/{action=Privacy}/{id?}");



app.Run();