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 routingUseAuthentication()— Handles login/authUseAuthorization()— Manages access controlUseStaticFiles()— 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).

Join the conversation! Your thoughts help the community grow.