ASP.NET Core Middleware is a core concept in ASP.NET Core that defines how HTTP requests and responses are handled in a web application.
Middleware components are assembled into a pipeline. Every request passes through this pipeline, and each middleware can:
- Process the request
- Pass it to the next middleware
- Or short-circuit (stop) the pipeline
What is Middleware?
Middleware is simply a piece of code that sits between the incoming HTTP request and the outgoing response.
Real-life analogy
Think of middleware like a pipeline of filters:
- Authentication
- Logging
- Routing
- Error handling
- Each step decides what to do next.
How Middleware Works
When a request comes in:
- It enters the middleware pipeline
- Each middleware executes in sequence
- Response flows back in reverse order
Request → Middleware1 → Middleware2 → Middleware3 → Response
Built-in Middleware in ASP.NET Core
ASP.NET Core provides many ready-to-use middleware components:
- Authentication Middleware
- Authorization Middleware
- Static Files Middleware
- Routing Middleware
- Exception Handling Middleware
- CORS Middleware
Configuring Middleware
Middleware is configured in the Program.cs (or Startup.cs in older versions).
Example:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
Types of Middleware Registration
1. Use
Calls the next middleware in pipeline
app.Use(async (context, next) =>
{
Console.WriteLine("Before next middleware");
await next();
Console.WriteLine("After next middleware");
});
2. Run
Terminates the pipeline (no next middleware)
app.Run(async context =>
{
await context.Response.WriteAsync("Hello World");
});
3. Map
Branches the pipeline based on URL
app.Map("/admin", adminApp =>
{
adminApp.Run(async context =>
{
await context.Response.WriteAsync("Admin Area");
});
});
Creating Custom Middleware
You can build your own middleware for custom logic.
Step 1: Create Middleware Class
public class MyMiddleware
{
private readonly RequestDelegate _next;
public MyMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
Console.WriteLine("Custom Middleware Start");
await _next(context);
Console.WriteLine("Custom Middleware End");
}
}
Step 2: Register Middleware
app.UseMiddleware<MyMiddleware>();
Middleware Execution Order (Important)
Order matters a lot in middleware.
Example:
app.UseAuthentication();
app.UseAuthorization();
If reversed:
app.UseAuthorization(); // Wrong
app.UseAuthentication();
Authorization will fail because the user is not authenticated yet.
Short-Circuiting Middleware
Middleware can stop the pipeline:
app.Use(async (context, next) =>
{
if (context.Request.Path == "/stop")
{
await context.Response.WriteAsync("Pipeline stopped");
return;
}
await next();
});
Benefits of Middleware
- Clean separation of concerns
- Reusable components
- Easy to plug/unplug features
- Centralized request handling
Common Use Cases
- Logging requests/responses
- Exception handling
- Authentication & Authorization
- Response compression
- API rate limiting
Conclusion
Middleware is the backbone of request processing in ASP.NET Core. By organizing logic into a pipeline, it allows developers to build scalable, maintainable, and high-performance web applications.
Understanding middleware is essential for:
- Building APIs
- Implementing security
- Improving performance