Middleware in ASP.NET Core is a software component that handles HTTP requests and responses as they move through the application pipeline.
Simple Definition
Middleware acts like a pipeline of components where each one can:
- Process an incoming request
- Modify it
- Pass it to the next component
- Or stop the request and return a response
How It Works
When a request comes into an ASP.NET Core app:
- It enters the middleware pipeline
- Each middleware component runs in sequence
Each can either:
- Call the next middleware
- Or handle the request and end the pipeline
Key Features
- Request/Response handling
- Modular and reusable
- Order matters (execution depends on registration order)
- Can short-circuit the pipeline
Common Built-in Middleware
- Authentication Middleware
- Authorization Middleware
- Exception Handling Middleware
- Static File Middleware
- Routing Middleware
Example
public void Configure(IApplicationBuilder app)
{
app.Use(async (context, next) =>
{
await context.Response.WriteAsync("Hello ");
await next();
await context.Response.WriteAsync("World!");
});
}
Output: Hello World!
In Short
Middleware in ASP.NET Core is the core mechanism that processes HTTP requests in a step-by-step pipeline, allowing developers to control how requests and responses are handled.