How To Make Custom Middleware In .NET 6.0

In order to avoid using in-line middleware in the Program.cs file, we will now create a custom middleware. Individual middleware will be created in a different class. Please find the considerations for creating custom middleware below.

The middleware class must include the following:

  • a public constructor with a RequestDelegate-type parameter.
  • either the Invoke or InvokeAsync public method. This technique ought to produce a Task.
  • HttpContext should be the type of the first parameter.
  • IApplicationBuilder is used to generate an extension method that exposes the middleware.
  • Through Dependency Injection, extra parameters for constructors and Invok/InvokeAsync can be filled in.

 

Let’s rapidly develop some middleware in Visual Studio. For this tutorial, I’ll be using the tools listed below:

 

  1. Visual Studio Community Edition 2022 (64-bit) – Preview (Version 17.3.0 Preview 4.0)
  2. .NET 6.0
  3. Minimal Web API
  4. Swagger

There are three methods for developing unique middleware.

Approach 1

  1. Right click on Project- > Add-> New Item
  2. Search for Middleware in the Pop-up window
  3. Select Middleware Class, providing a meaningful name and click on “Add”

A class will be created as below with the default implementation:

namespace MiddlewareTutorial {
    // You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project
    public class LoggingMiddleware {
        private readonly RequestDelegate _next;
        public LoggingMiddleware(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 LoggingMiddlewareExtensions {
        public static IApplicationBuilder UseLoggingMiddleware(this IApplicationBuilder builder) {
            return builder.UseMiddleware < LoggingMiddleware > ();
        }
    }
}

 

Approach 2

  1. Create a new class and give it a clever name.
  2. Include the public constructor with a RequestDelegate-type parameter.
  3. Create a method called Invoke/InvokeAsync that has Task as its return type and HttpContext as its first parameter.
  4. To expose the middleware, add an extension method using IApplicationBuilder.

The final class will be looks like below:

namespace MiddlewareTutorial {
    public class ClassWithNoImplementationMiddleware {
        private readonly RequestDelegate _next;
        public ClassWithNoImplementationMiddleware(RequestDelegate next) {
            _next = next;
        }
        public async Task InvokeAsync(HttpContext httpContext) {
            await httpContext.Response.WriteAsync("Hello Readers!, this from Customer Middleware...");
        }
    }
    // Extension method used to add the middleware to the HTTP request pipeline.
    public static class ClassWithNoImplementationMiddlewareExtensions {
        public static IApplicationBuilder UseClassWithNoImplementationMiddleware(this IApplicationBuilder builder) {
            return builder.UseMiddleware < ClassWithNoImplementationMiddleware > ();
        }
    }
}

 

Approach 3

  1. Create a class with a meaningful name
  2. Implement the interface IMiddleware

The class will look like the below:

namespace MiddlewareTutorial {
    public class ClassWithIMiddlewareInterface: IMiddleware {
        public Task InvokeAsync(HttpContext context, RequestDelegate next) {
            throw new NotImplementedException();
        }
    }
}

 

Let’s fast examine a straightforward example of custom middleware and how Program.cs can use it. I’ll employ the sample code from Approach 2 here.

public async Task InvokeAsync(HttpContext httpContext) {
    await httpContext.Response.WriteAsync("Hello Readers, this is from Custom Middleware...");
}

 

Now let us use this middleware into Program.cs class.

using MiddlewareTutorial;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment()) {
    app.UseClassWithNoImplementationMiddleware();
    app.UseSwagger();
    app.UseSwaggerUI();
}
app.Run();

 

The output will look like the below:

I appreciate you reading the content. I trust you now have a better knowledge of how to make custom middleware. Please share your thoughts in the space provided below.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories