1. 🔹 What is Middleware?
  2. 🔹 How Middleware Works
  3. 🔹 Example: Creating Custom Middleware
  4. 🔹 Common Built-in Middleware in ASP.NET Core
  5. 🔹 Summary

When building modern web applications with ASP.NET Core, one of the most important concepts to understand is middleware. Middleware forms the backbone of the request and response pipeline, giving developers complete control over how HTTP requests are processed.


🔹 What is Middleware?

Middleware is simply a component that sits in the pipeline and handles requests and responses. Each middleware can:

  1. Receive the incoming request.
  2. Perform an action (such as logging, authentication, routing, or caching).
  3. Pass the request to the next middleware in the chain.
  4. Process the response before it is returned to the client.

This pipeline-based architecture makes ASP.NET Core flexible and highly customizable.


🔹 How Middleware Works

  • Middleware components are executed in the order they are added to the application pipeline.
  • Each component decides whether to:
    • Continue to the next middleware (await next()), or
    • Short-circuit the pipeline (for example, returning an error or a static response immediately).

This flow allows developers to handle cross-cutting concerns like logging, exception handling, authentication, and more, in a structured way.


🔹 Example: Creating Custom Middleware

Let’s create a simple middleware that logs incoming requests and outgoing responses.

public class CustomMiddleware
{
    private readonly RequestDelegate _next;

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

    public async Task InvokeAsync(HttpContext context)
    {
        // Before next middleware
        Console.WriteLine("Handling request: " + context.Request.Path);

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

        // After next middleware
        Console.WriteLine("Finished handling request.");
    }
}

// Extension method for cleaner registration
public static class CustomMiddlewareExtensions
{
    public static IApplicationBuilder UseCustomMiddleware(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<CustomMiddleware>();
    }
}

To register this middleware, update your Program.cs:

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

app.UseCustomMiddleware(); // Add custom middleware
app.UseRouting();
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});

app.Run();

🔹 Common Built-in Middleware in ASP.NET Core

ASP.NET Core comes with many powerful built-in middleware components, including:

  • UseRouting() → Matches requests to routes.
  • UseAuthentication() → Validates the user’s identity.
  • UseAuthorization() → Enforces access control.
  • UseStaticFiles() → Serves CSS, JS, images, and other static content.
  • UseExceptionHandler() → Handles global exceptions gracefully.
  • UseEndpoints() → Executes the matched endpoint logic.

🔹 Summary

Middleware in ASP.NET Core acts as a chain of responsibility for handling HTTP requests and responses. Each component can intercept, modify, or short-circuit requests before they reach your application logic.

By combining built-in middleware with custom ones, developers can build clean, modular, and maintainable applications.