Custom Middleware in .Net core 6.0

 

We will now write a custom middleware to avoid inline middleware in Program.cs.  The custom middleware will be written to a different class. Please keep the following in mind when writing custom middleware.

There are several components that must be included in the middleware class:

  • RequestDelegate is a public constructor with a parameter.
  • Invoke or InvokeAsync is a public method that should return a Task.
  • HttpContext should be the first parameter
  • With IApplicationBuilder, an extension method is created for exposing the Middleware.
  • Dependency Injection can be used to populate additional parameters for the constructor and for Invok/InvokeAsync.


Let's quickly dive into Visual Studio and start building a middleware. In this tutorial, I'll be utilizing the following tools:

  • Visual Studio Community Edition 2022 (64-bit)
  • .NET 6.0
  • Minimal Web API
  • Swagger


There are three different methods or approaches you can use to create your own custom middleware.

Method 1

  • First of all you can Right Click on the Project -> Add -> New Item.
  • After You will find out for that Middleware in the Pop-up window.
  • then, Select the Middleware class and given the proper name and click on 'Add'.

Add Middleware

A class will be created in this way with the default implementation:


 
 		namespace CustomMiddleware
{
    
    public class CustomMiddleware
    {
        private readonly RequestDelegate _next;

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

        public Task Invoke(HttpContext httpContext)
        {

            return _next(httpContext);
        }
    }

    
    public static class CustomMiddlewareExtensions
    {
        public static IApplicationBuilder UseCustomMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<CustomMiddleware>();
        }
    }
}     
      


Method 2
  • Insert a new class with a significant name.
  • Add the public constructor using the RequestDelegate argument.
  • Implement an Invoke/InvokeAsync method with a first parameter of HttpContext and a return type of Task.
  • Add a method of extension through IApplicationBuilder to expose the middleware.

  namespace CustomMiddleware
{
    public class NoImplementationCustomMiddleware
    {
        private readonly RequestDelegate _next;
        public NoImplementationCustomMiddleware(RequestDelegate next)
        {
            _next = next;
        }
        public async Task InvokeAsync(HttpContext httpContext)
        {
            await httpContext.Response.WriteAsync("Hello Friends !, this is my Customer Middleware...");
        }
    }
   
    public static class NoImplementationCustomMiddlewareExtensions
    {
        public static IApplicationBuilder UseClassWithNoImplementationMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<NoImplementationCustomMiddleware>();
        }
    }
}
  

Method 3
  • Insert a new class with a significant name.
  • Now Implement of the interface of the Middleware

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


Now we can use the Custom Middleware into the Program.cs

        using CustomMiddleware;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();
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.UseHttpsRedirection();
//app.UseStaticFiles();

//app.UseRouting();

//app.UseAuthorization();

//app.MapRazorPages();

app.Run();

        

Comments