Creating Custom Middleware in ASP.NET

What is Custom Middleware?

Middleware in ASP.NET Core processes HTTP requests and responses in a pipeline. While ASP.NET provides built-in middleware, you can create custom middleware to handle specific application requirements, such as logging, authentication, or modifying responses.

  • Custom Logic: Define unique behaviors for requests and responses.
  • Pipeline Control: Decide how and when to pass control to the next middleware.
  • Reusability: Use custom middleware across multiple projects.

Steps to Create and Use Custom Middleware

Follow these steps to create and use custom middleware in an ASP.NET Core application:

1. Create a Middleware Class


// Middleware/CustomHeaderMiddleware.cs
public class CustomHeaderMiddleware
{
    private readonly RequestDelegate _next;

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

    public async Task InvokeAsync(HttpContext context)
    {
        // Before the next middleware
        Console.WriteLine("Custom middleware executing before the next middleware.");

        // Call the next middleware
        await _next(context);

        // After the next middleware
        context.Response.Headers.Add("X-Custom-Header", "MiddlewareDemo");
        Console.WriteLine("Custom middleware executing after the next middleware.");
    }
}

                

The CustomHeaderMiddleware adds a custom HTTP response header and logs messages during request and response processing.

2. Create an Extension Method


// Extensions/MiddlewareExtensions.cs
public static class MiddlewareExtensions
{
    public static IApplicationBuilder UseCustomHeaderMiddleware(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<CustomHeaderMiddleware>();
    }
}

                

The extension method UseCustomHeaderMiddleware makes it easier to add the middleware to the request pipeline.

3. Register Middleware in the Pipeline


// Program.cs
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

// Add custom middleware
app.UseCustomHeaderMiddleware();

app.MapGet("/", () => "Welcome to Custom Middleware Demo!");

app.Run();

                

Use the extension method to add the middleware to the pipeline.

4. Test Custom Middleware


// Example Request
GET / HTTP/1.1

// Example Response
HTTP/1.1 200 OK
X-Custom-Header: MiddlewareDemo
Content-Type: text/plain; charset=utf-8

Welcome to Custom Middleware Demo!

                

Observe the response header X-Custom-Header to verify that the custom middleware executed correctly.


Key Benefits of Custom Middleware

  • Flexibility: Define application-specific logic.
  • Pipeline Customization: Control how requests and responses are processed.
  • Modular Design: Separate concerns into independent components.