Introduction

In ASP.NET Core, middleware is software that sits in the request pipeline and handles HTTP requests and responses. Each middleware component can perform operations before and after passing control to the next component.

Middleware is powerful because it allows developers to customize request handling, implement cross-cutting concerns (like logging, authentication, error handling), and keep the application modular.

What is Middleware?

Examples of built-in middleware:

Example: Custom Request Logging Middleware

Imagine you want to log every incoming request’s path and execution time. Instead of adding logging code in every controller, you can create a custom middleware.

Step 1: Create Middleware Class

public class RequestLoggingMiddleware
{
    private readonly RequestDelegate _next;

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

    public async Task InvokeAsync(HttpContext context)
    {
        var startTime = DateTime.UtcNow;

        // Log request path
        Console.WriteLine($"Incoming Request: {context.Request.Path}");

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

        var duration = DateTime.UtcNow - startTime;
        Console.WriteLine($"Request {context.Request.Path} completed in {duration.TotalMilliseconds} ms");
    }
}

Step 2: Extension Method for Clean Registration

public static class RequestLoggingMiddlewareExtensions
{
    public static IApplicationBuilder UseRequestLogging(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<RequestLoggingMiddleware>();
    }
}

Step 3: Register Middleware in Program.cs

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

// Custom middleware
app.UseRequestLogging();

// Built-in middleware
app.UseRouting();
app.UseAuthorization();

app.MapControllers();
app.Run();

Example in Action

Custom Middleware Ideas

Conclusion

Middleware in ASP.NET Core provides a flexible way to handle cross-cutting concerns. By creating custom middleware, you can centralize logic like logging, error handling, or security checks. Our Request Logging Middleware example demonstrates how easy it is to extend the pipeline with custom behavior.