Middleware in ASP.NET Core is a fundamental concept used to build the HTTP request pipeline. Each middleware component in the pipeline:
-
Processes incoming HTTP requests.
-
Optionally short-circuits the pipeline (e.g., for authentication).
-
Passes control to the next middleware.
-
Optionally processes the outgoing HTTP response.
What is Middleware?
Middleware is software that's assembled into an application pipeline to handle requests and responses. Each component:
-
Can perform work before and after the next delegate (middleware) is invoked.
-
Can terminate the request pipeline early.
-
Can perform asynchronous operations.
Request Pipeline Structure
Here’s a simple visualization:
Middleware Lifecycle
Each middleware is a RequestDelegate
:
public delegate Task RequestDelegate(HttpContext context);
Creating Custom Middleware
You can create custom middleware by either:
1. Class-based Middleware
{
private readonly RequestDelegate _next;
public MyMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
// Pre-processing logic
Console.WriteLine("Request: " + context.Request.Path);
await _next(context);
// Call the next middleware
// Post-processing logic
Console.WriteLine("Response: " + context.Response.StatusCode);
}
}
Register it in Startup.cs
:
2. Inline Middleware (Lambda)
{
Console.WriteLine("Before");
await next.Invoke();
Console.WriteLine("After");
}
);
Built-in Middleware Examples
ASP.NET Core includes many built-in middleware components:
Middleware | Description |
---|---|
UseStaticFiles |
Serves static files like images, JS, CSS |
UseRouting |
Routes requests to endpoints |
UseAuthentication |
Authenticates the user |
UseAuthorization |
Authorizes access based on policies/roles |
UseEndpoints |
Maps endpoints to controllers or Razor pages |
UseExceptionHandler |
Global exception handling |
UseHttpsRedirection |
Redirects HTTP requests to HTTPS |
UseCors |
Configures Cross-Origin Resource Sharing (CORS) |
UseSession |
Enables session state |
Order Matters
The order of middleware registration in Configure()
is critical. For example:
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(...);
Putting UseAuthentication()
after UseEndpoints()
would result in no authentication.
Best Practices
-
Keep middleware focused on one responsibility.
-
Handle exceptions early in the pipeline.
-
Use inline middleware for short logic, classes for complex logic.
-
Avoid long blocking operations – use async/await.