ASP.NET Core  

How to Create Custom Middleware in ASP.NET Core

What is Middleware?

In ASP.NET Core, a middleware is a small software component that processes HTTP requests and responses.
Each middleware runs in a pipeline, and can:

  • Perform an action before the next middleware runs,

  • Perform an action after it runs, or

  • Even stop the request from continuing further.

In simple words: Middleware is like a checkpoint in the request pipeline that can inspect, modify, or terminate the request/response.

Default Middleware Examples

ASP.NET Core comes with built-in middleware such as:

  • UseRouting() — Handles URL routing

  • UseAuthentication() — Handles login/auth

  • UseAuthorization() — Manages access control

  • UseStaticFiles() — Serves static files like images or CSS

You can also create your own custom middleware to add specific logic (like logging, validation, or tracking).

Step-by-Step: Creating Custom Middleware

Let’s create a simple custom middleware that logs each incoming request and outgoing response.

Step 1. Create the Middleware Class

using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
using System;

public class MyCustomMiddleware
{
    private readonly RequestDelegate _next;

    // Constructor to accept the next middleware in the pipeline
    public MyCustomMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    // Main method to handle request and response
    public async Task InvokeAsync(HttpContext context)
    {
        // Code before the next middleware runs
        Console.WriteLine($" Request received: {context.Request.Method} {context.Request.Path}");

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

        // Code after the next middleware runs
        Console.WriteLine($" Response sent: {context.Response.StatusCode}");
    }
}

Step 2. Create an Extension Method (for cleaner code)

It’s good practice to add an extension method so you can easily use your middleware.

using Microsoft.AspNetCore.Builder;

public static class MyCustomMiddlewareExtensions
{
    public static IApplicationBuilder UseMyCustomMiddleware(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<MyCustomMiddleware>();
    }
}

Step 3. Register the Middleware in Program.cs

In .NET 6+, middleware is added in the request pipeline using the app object.

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

// Custom middleware registration
app.UseMyCustomMiddleware();

// Example controller routing
app.MapControllers();

app.Run();

Step 4. Run and Test

Now run your application (Ctrl + F5).

When you send a request (like GET /api/values), you’ll see logs in the console:

 Request received: GET /api/values
 Response sent: 200

Your custom middleware successfully intercepted and logged the request and response!

How Middleware Works Internally

When a request comes in:

  1. The first middleware receives it.

  2. It can do something (like logging) and call the next middleware.

  3. The request flows through all middleware components.

  4. The response flows back through them in reverse order.

Visual Flow Diagram

Request → [Middleware 1] → [Middleware 2] → [Middleware 3] → Endpoint
             ↑                                      ↓
          Response ← [Middleware 3] ← [Middleware 2] ← [Middleware 1]

When to Use Custom Middleware

Custom middleware is useful for:

  • Logging requests and responses

  • Handling exceptions globally

  • Adding custom headers or tokens

  • Measuring performance

  • Implementing request filters (e.g., IP blocking)

Example: Adding a Header Middleware

Here’s another short example that adds a custom header to all responses:

public class HeaderMiddleware
{
    private readonly RequestDelegate _next;

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

    public async Task InvokeAsync(HttpContext context)
    {
        await _next(context);
        context.Response.Headers.Add("X-Powered-By", "SandhiyaCustomMiddleware");
    }
}

Register it in Program.cs:

app.UseMiddleware<HeaderMiddleware>();

Every response from your app will now include:

X-Powered-By: SandhiyaCustomMiddleware

Summary

StepAction
1Create a middleware class with InvokeAsync(HttpContext)
2Add an extension method for better reusability
3Register it in the request pipeline using the app.UseMyCustomMiddleware()
4Test by sending a request and checking the console or response headers

Conclusion

Custom middleware gives you complete control over the request and response pipeline in ASP.NET Core.

It helps you write clean, reusable, and centralized logic for logging, authentication, or any pre/post-processing.

In short: Middleware is the heart of ASP.NET Core request handling — and custom middleware lets you extend that heart for your unique business needs.