Site icon Tutexchange

Creating Custom ASP.NET Core Middleware

Advertisements

In this article, we will walk through the process of creating a custom middleware in an ASP.NET Core application and registering it in the Startup class.

Middleware is a fundamental concept in ASP.NET Core that allows developers to handle HTTP requests and responses as they pass through a pipeline. You can use middleware for tasks such as logging, authentication, error handling, request modification, and more.

What is Middleware?

Middleware is a software component that is executed on every HTTP request. It either:

Each middleware component in ASP.NET Core is executed in the order in which it’s added to the pipeline.

Step 1: Create a New ASP.NET Core Application

We will create a new ASP.NET Core web application named DemoWebApplication.

Using Visual Studio:

  1. Open Visual Studio
  2. Select Create a new project
  3. Choose ASP.NET Core Web App (Model-View-Controller)
  4. Name it DemoWebApplication
  5. Click Create

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

Summary

Exit mobile version