Every time a user visits an ASP.NET Core application, sends an API request, or submits a form, that request passes through a series of components before reaching its destination.
These components are called middleware.
Middleware plays an important role in ASP.NET Core because it allows developers to handle requests and responses in a flexible and reusable way. Instead of repeating logging, authentication, error handling, or other logic across controllers, middleware allows these responsibilities to be handled centrally.
Understanding middleware is essential for building maintainable, secure, and scalable ASP.NET Core applications.
In this article, we will explore how middleware works, how to create custom middleware, and how to use it in real-world applications.
1. What Is Middleware?
Middleware is software that is assembled into an application's request-processing pipeline.
Each middleware component can:
- Process an incoming HTTP request.
- Pass the request to the next middleware.
- Process the response after the next middleware completes.
- Stop the pipeline and return a response without invoking the next component.
For example, when a user requests a page, the request may pass through several middleware components:
- Exception handling
- HTTPS redirection
- Static file handling
- Routing
- Authentication
- Authorization
- Controller execution
Each component performs a specific task.
How the middleware pipeline works
flowchart TD
A[Incoming HTTP Request] --> B[Exception Middleware]
B --> C[HTTPS Middleware]
C --> D[Static File Middleware]
D --> E[Routing Middleware]
E --> F[Authentication Middleware]
F --> G[Authorization Middleware]
G --> H[Controller / Endpoint]
H --> I[HTTP Response]
I --> G
G --> F
F --> E
E --> D
D --> C
C --> B
B --> J[Response Sent to Client]
Middleware executes in the order in which it is registered.
The request travels forward through the pipeline, while the response unwinds through middleware that has additional processing after the next component returns.
2. Understanding the Middleware Pipeline in Program.cs
In modern ASP.NET Core applications, middleware is configured in Program.cs.
For example:
var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); var app = builder.Build(); app.UseHttpsRedirection(); app.UseAuthentication(); app.UseAuthorization(); app.MapControllers(); app.Run();
Each Use... method adds middleware to the pipeline.
The order matters because middleware may depend on other middleware being executed first.
For example, authentication should run before authorization because authorization needs to know who the current user is.
app.UseAuthentication(); app.UseAuthorization();
Reversing these two calls can result in authorization decisions being made before authentication has established the user's identity.
Middleware ordering is one of the most important concepts to understand when debugging ASP.NET Core applications.
3. Create Your First Custom Middleware
Let's create a simple middleware that logs when a request enters and leaves the application.
This can help us understand how middleware works internally.
Step 1: Create the Middleware Class
Create a class called RequestLoggingMiddleware.cs.
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
public class RequestLoggingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<RequestLoggingMiddleware> _logger;
public RequestLoggingMiddleware(
RequestDelegate next,
ILogger<RequestLoggingMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
_logger.LogInformation(
"Incoming Request: {Method} {Path}",
context.Request.Method,
context.Request.Path);
await _next(context);
_logger.LogInformation(
"Response Status Code: {StatusCode}",
context.Response.StatusCode);
}
}
Let's understand the important parts.
RequestDelegate
private readonly RequestDelegate _next;
RequestDelegate represents the next component in the middleware pipeline.
Calling:
await _next(context);
passes the current HTTP context to the next middleware.
If you don't call _next, the request will not continue to subsequent middleware.
InvokeAsync
public async Task InvokeAsync(HttpContext context)
ASP.NET Core invokes this method when the middleware processes a request.
The middleware can access information about the request and response through HttpContext.
Before and after the next middleware
The following code executes before the next middleware:
_logger.LogInformation("Incoming Request");
This code executes after the next middleware completes:
await _next(context);
_logger.LogInformation("Request Completed");
This behavior makes middleware useful for logging request duration, handling exceptions, modifying responses, and other operations.
4. Register Custom Middleware
Once the middleware class is created, register it in Program.cs.
var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); var app = builder.Build(); app.UseMiddleware<RequestLoggingMiddleware>(); app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run();
Now every request that reaches this middleware will be logged.
Example output:
Incoming Request: GET /api/products Response Status Code: 200 Incoming Request: POST /api/products Response Status Code: 201
This is useful when monitoring application behavior or investigating unexpected HTTP responses.
5. Create Middleware to Measure Request Execution Time
Request performance monitoring is another practical use of middleware.
Instead of measuring execution time separately in every controller, we can create middleware that measures how long each request takes.
using System.Diagnostics;
public class RequestTimingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<RequestTimingMiddleware> _logger;
public RequestTimingMiddleware(
RequestDelegate next,
ILogger<RequestTimingMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
var stopwatch = Stopwatch.StartNew();
await _next(context);
stopwatch.Stop();
_logger.LogInformation(
"{Method} {Path} completed in {ElapsedMilliseconds} ms",
context.Request.Method,
context.Request.Path,
stopwatch.ElapsedMilliseconds);
}
}
Register it:
app.UseMiddleware<RequestTimingMiddleware>();
Example output:
GET /api/products completed in 48 ms GET /api/customers completed in 123 ms POST /api/orders completed in 865 ms
This helps identify slow endpoints and gives developers an initial understanding of request performance.
For production applications, consider using built-in logging, tracing, metrics, and observability tools for more comprehensive monitoring.
6. Middleware Can Short-Circuit the Pipeline
Middleware does not always need to call the next component.
If it generates a response itself, it can stop the pipeline.
For example, let's create middleware that blocks requests from a specific path.
public class MaintenanceMiddleware
{
private readonly RequestDelegate _next;
public MaintenanceMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
if (context.Request.Path.StartsWithSegments("/maintenance"))
{
context.Response.StatusCode =
StatusCodes.Status503ServiceUnavailable;
await context.Response.WriteAsync(
"The service is temporarily unavailable.");
return;
}
await _next(context);
}
}
Register it:
app.UseMiddleware<MaintenanceMiddleware>();
When the user requests:
https://example.com/maintenance
The middleware returns a 503 Service Unavailable response.
The controller or endpoint is never executed.
This behavior is called short-circuiting.
It can be useful for:
- Maintenance mode
- Request validation
- IP restrictions
- Rate limiting
- API key validation
- Feature restrictions
However, authentication, authorization, and security-related checks should generally use the appropriate built-in ASP.NET Core features rather than custom implementations unless there is a specific requirement.
7. Create Middleware for Exception Handling
Exception handling is another important middleware responsibility.
Instead of allowing unexpected exceptions to produce inconsistent responses, we can centralize exception handling.
For example:
public class ExceptionHandlingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<ExceptionHandlingMiddleware> _logger;
public ExceptionHandlingMiddleware(
RequestDelegate next,
ILogger<ExceptionHandlingMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
_logger.LogError(
ex,
"An unexpected error occurred.");
if (context.Response.HasStarted)
{
throw;
}
context.Response.Clear();
context.Response.StatusCode =
StatusCodes.Status500InternalServerError;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(
new
{
message = "An unexpected error occurred.",
statusCode = 500
});
}
}
}
Register this middleware early in the pipeline:
app.UseMiddleware<ExceptionHandlingMiddleware>();
Because it is registered early, it can catch exceptions thrown by middleware and endpoints that execute later.
In production, avoid returning internal exception details, stack traces, database errors, or sensitive information to clients.
For most applications, the built-in exception handling middleware is preferable:
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
}
For API applications, you can also use centralized exception handling with Problem Details responses.
Custom exception middleware is useful when you need a specific response format, logging behavior, or integration with your application's error-handling strategy.
8. Middleware Ordering Explained
Middleware ordering directly affects application behavior.
Consider this configuration:
app.UseAuthentication(); app.UseAuthorization(); app.MapControllers();
Authentication identifies the current user.
Authorization determines whether that user is allowed to access a resource.
Therefore, authentication must generally be registered before authorization.
Another example is exception handling:
app.UseExceptionHandler("/Error");
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
Exception handling is placed near the beginning of the pipeline so that it can handle exceptions from downstream middleware.
Common middleware ordering mistakes
MiddlewareTypical considerationException handlingUsually placed earlyHTTPS redirectionBefore endpoints that should enforce HTTPSStatic filesUsually before authentication when public files are intendedRoutingBefore middleware that depends on endpoint informationCORSPositioned appropriately before endpoint executionAuthenticationBefore authorizationAuthorizationBefore protected endpointsEndpoint mappingAfter required middleware
The exact ordering depends on your application's requirements.
For example, if static files must be protected, the standard public static-file middleware may not be sufficient; you may need an authenticated endpoint or another approach to serve those files.
9. Middleware vs Filters
Developers sometimes confuse middleware with MVC filters.
Both can execute code before and after certain operations, but they operate at different levels.
Middleware
Middleware belongs to the HTTP request pipeline.
It can run for a broad range of requests, including requests that don't reach MVC controllers.
Examples:
- Logging
- Exception handling
- Authentication
- Request timing
- HTTPS redirection
MVC Filters
Filters operate within the MVC or controller execution pipeline.
They are useful when you need behavior associated specifically with controller actions.
Examples:
- Action logging
- Action-specific validation
- Authorization rules
- Result modification
- Custom action execution
A simplified comparison:
MiddlewareFiltersWorks at HTTP pipeline levelWorks within MVC executionCan apply to the entire applicationApplies to MVC actions/controllersCan short-circuit the entire pipelineCan short-circuit specific MVC stagesSuitable for request-wide concernsSuitable for controller/action-specific concerns
For example, if you want to log every HTTP request, middleware is a good choice.
If you want to perform custom validation specifically before certain controller actions, an action filter may be more appropriate.
10. Middleware and Dependency Injection
Middleware can also use services registered in ASP.NET Core's dependency injection container.
For example, our logging middleware already uses:
ILogger<RequestLoggingMiddleware>
This is injected through the constructor.
However, middleware created using conventional UseMiddleware<T>() is generally constructed once for the application pipeline, not once per request.
This means scoped services such as DbContext should not normally be injected into the middleware constructor.
If middleware needs a scoped service, inject it into the InvokeAsync method:
public async Task InvokeAsync(
HttpContext context,
ApplicationDbContext dbContext)
{
// Use dbContext for this request
await _next(context);
}
ASP.NET Core resolves the scoped service for the current request.
This is important when middleware interacts with databases, request-specific services, or user-related data.
Avoid storing request-specific information in middleware instance fields because the same middleware instance may handle multiple requests concurrently.
11. When Should You Create Custom Middleware?
Custom middleware is useful when the same behavior needs to be applied consistently across multiple requests or endpoints.
Consider implementing middleware for:
- Centralized request logging
- Correlation IDs
- Request timing
- Global exception handling
- Custom headers
- Maintenance mode
- Request validation
- Tenant resolution
- Custom request processing
However, not every piece of logic belongs in middleware.
Business operations such as calculating order totals, approving loans, processing payments, or managing inventory should generally live in application services rather than middleware.
Middleware should focus on HTTP request-processing concerns that apply across the application or a defined group of endpoints.
Conclusion
Middleware is one of the most powerful features of ASP.NET Core. It provides a flexible way to handle HTTP requests and responses through a pipeline of reusable components.
By understanding how middleware executes, how RequestDelegate works, how components can short-circuit requests, and why ordering matters, developers can build cleaner and more maintainable applications.
Whether you're implementing request logging, performance monitoring, exception handling, authentication, or custom headers, middleware allows you to centralize these responsibilities instead of duplicating them throughout your controllers.
The key is to use middleware for cross-cutting HTTP concerns and keep application-specific business logic in services.
Once you understand the request pipeline, debugging ASP.NET Core applications becomes much easier — and building new features becomes more organized and predictable.