Middleware and filters both let you intercept HTTP requests in ASP.NET Core, but they operate at different levels: middleware runs on the entire request pipeline before and after the MVC layer, while filters run inside the MVC action invocation pipeline, wrapping the execution of actions, results, and exceptions. This article explains the exact role of each, how they differ, and how to choose the right one for common scenarios like authentication, logging, validation, and caching.
What Is Middleware in ASP.NET Core?
Middleware is software that is assembled into an application pipeline to handle requests and responses. Each middleware component in ASP.NET Core is a class with a RequestDelegate parameter in its constructor and a Invoke or InvokeAsync method. The pipeline is built in Program.cs using app.Use... extension methods, and each piece can choose to pass the request to the next middleware or short-circuit the pipeline by not calling next.
Middleware is the first thing that sees an incoming request and the last thing that sees the outgoing response. It is ideal for cross-cutting concerns that apply to every request, regardless of whether the request reaches an MVC action. Examples include:
- HTTPS redirection and HTTP strict transport security (HSTS)
- Static file serving
- Routing and endpoint selection
- Authentication (the
UseAuthenticationmiddleware) - Request logging and telemetry
- Error handling (e.g.,
UseExceptionHandler)
Middleware runs in the order it is added to the pipeline. This ordering is crucial because, for example, you typically want exception handling middleware early so it can catch exceptions from everything that follows.
What Are Filters in ASP.NET Core?
Filters are MVC-specific components that run within the MVC action invocation pipeline. They are attributes or classes that implement interfaces such as IActionFilter, IResultFilter, IExceptionFilter, or IAuthorizationFilter. Filters run after routing and model binding but before the action method executes, and they can also run after the action returns a result.
There are several types of filters, each with a specific purpose:
- Authorization filters – run first to determine if the user is authorized to access the action.
- Resource filters – run after authorization and can short-circuit the pipeline (useful for caching).
- Action filters – wrap the execution of the action method (e.g., logging, validation, modifying arguments).
- Exception filters – handle exceptions thrown by the action or other filters.
- Result filters – wrap the execution of the action result (e.g., adding headers to the response).
Filters are scoped to MVC controllers and actions. You can apply them globally, per-controller, or per-action using attributes. This makes them perfect for concerns that are specific to MVC actions, such as validating model state or formatting a response.
Key Differences: Pipeline vs. Action Invocation
The fundamental difference is the layer at which each operates. Middleware is part of the HTTP request pipeline and runs for every request, even those that do not hit an MVC endpoint (like static files or health checks). Filters only run when an MVC action is about to execute.
Another important difference is access to MVC context. Filters have access to ActionExecutingContext, ResultExecutingContext, and other MVC-specific objects, which contain rich information about the action, its arguments, and the model state. Middleware only sees the HttpContext and cannot directly inspect or modify action arguments.
Order of execution also differs. Middleware runs in the order it is registered, while filters run in a well-defined sequence: authorization filters, resource filters, action filters, exception filters, then result filters. Within each type, you can set the Order property to control execution order.
How to Choose: Middleware or Filter?
The choice comes down to the scope of the concern and the need for MVC-specific data. Ask yourself:
- Does this need to run for every request, even non-MVC endpoints? → Middleware
- Do I need access to action arguments, model state, or the action result? → Filter
- Is this a cross-cutting infrastructure concern (like HTTPS or logging) that should be applied globally? → Middleware
- Is this a concern that only applies to certain controllers or actions? → Filter
For example, if you want to log every HTTP request to your API, middleware is the right choice because it will capture all requests, including those that fail before reaching MVC. If you want to log the execution time of a specific action method, an action filter is more appropriate because it can access the action's context and measure the time around the action's execution.
If you are building a custom authentication or authorization mechanism, you might use middleware for authentication (to set the user principal) and an authorization filter for checking permissions on specific actions. This is the standard pattern in ASP.NET Core.
Common Pitfalls and Misconceptions
One common misconception is that middleware and filters are interchangeable. They are not. Trying to access MVC-specific features like IAsyncActionFilter from middleware is impossible because middleware does not have access to the action context. Conversely, using a filter for a global concern like request logging will miss requests that do not reach MVC (e.g., static files or 404s).
Another pitfall is incorrect ordering. Middleware order matters: if you add authentication middleware after the MVC middleware, the authentication will not run for MVC requests. Similarly, if you add a filter that modifies the response but the result filter runs after the action result has already been written, it may be too late to change the body.
Performance can also be a concern. Middleware runs on every request, so heavy middleware can slow down static file serving. Filters run only on MVC actions, so they are more targeted but can still be a bottleneck if they perform expensive operations like database calls.
Real-World Examples
Here are concrete scenarios to illustrate the decision:
- Request logging: Use middleware. You want to log every request, including those that fail in routing or return 404. A filter would miss those.
- Model validation: Use an action filter. You need to inspect the
ModelStateand return a 400 response if invalid. This is MVC-specific and only relevant to actions. - Caching responses: Use a resource filter. It can short-circuit the pipeline before the action runs, returning a cached response. Middleware could do this too, but a resource filter has access to the action context, making it easier to generate cache keys based on action parameters.
- Global exception handling: Use middleware (like
UseExceptionHandler) for unhandled exceptions across the whole app, but use an exception filter for exceptions that occur within MVC actions where you want to return a specific error response with details from the action context. - Adding security headers: Use middleware. It applies to all responses, including static files, and does not need MVC context.
Performance and Overhead Considerations
Both middleware and filters add overhead, but the impact is usually negligible if used judiciously. Middleware runs on every request, so a middleware that performs heavy synchronous I/O could block the thread pool. Use asynchronous middleware (InvokeAsync) and avoid blocking calls.
Filters are instantiated per request (unless registered as singletons), so they have a small allocation cost. If a filter is stateless, you can register it as a singleton to reduce allocations. However, be cautious with singleton filters that hold state because they are shared across requests.
When performance is critical, consider using middleware for simple, high-frequency operations (like adding a header) and filters for operations that need MVC context. Also, remember that middleware can short-circuit the pipeline, which can improve performance by skipping unnecessary processing.
Frequently Asked Questions
Can I use both middleware and filters for the same concern?
Yes, you can. For example, you might use middleware for basic request logging and an action filter for logging detailed execution time of actions. Just be aware that they run at different stages, and you might get duplicate logs if you are not careful.
Do filters run before or after middleware?
Middleware runs first in the request pipeline. After the middleware chain calls the endpoint, the MVC framework invokes the filters. So middleware runs before filters on the way in, and after filters on the way out (because the response passes back through the middleware chain).
Can I access HttpContext in a filter?
Yes, filters have access to HttpContext via the FilterContext (e.g., ActionExecutingContext.HttpContext). This allows you to read request headers, write to the response, or access services from the request's RequestServices.
Is middleware the same as OWIN middleware?
ASP.NET Core middleware is conceptually similar to OWIN middleware, but it is a new implementation. OWIN was the interface for .NET Framework, while ASP.NET Core uses its own RequestDelegate model. You can still run OWIN middleware in ASP.NET Core using the UseOwin extension, but it is rarely needed.
When should I use a custom middleware instead of a built-in one?
You should write custom middleware when you need to handle a cross-cutting concern that is not covered by the built-in middleware (like UseStaticFiles or UseAuthentication). Examples include request rate limiting, custom logging, or modifying request/response headers.
Can filters be used in minimal APIs?
No, filters are part of the MVC framework and do not apply to minimal APIs. In minimal APIs, you use middleware and endpoint filters (introduced in .NET 7) instead. Endpoint filters are similar to action filters but are specific to minimal API endpoints.