Filters and Middlewares
Filters in ASP.NET Core are a way to add additional behavior to the MVC framework's request processing pipeline. Filters are C# classes that can be applied to controllers, actions, or globally across all controllers and actions.
Here's a breakdown of the types of filters available in ASP.NET Core:
Authorization Filters: These handle authorization aspects, determining whether a user is allowed to perform a certain action or access specific resources.
Resource Filters: These filters run before the model binding stage, so you can access the raw HTTP request. They also run after the execution of the action result, so they can manipulate the HTTP response.
Action Filters: These handle additional processing related to action method execution, such as caching and logging. They can execute both before and after an action method.
Exception Filters: These are used for handling and logging exceptions that occur during controller action execution.
Result Filters: These allow you to run code immediately before and after the execution of action results. They're often used for modifying the view data or manipulating the response sent to the client.
Filters can be set at different scope levels:
Global Filters: These apply to all actions and controllers.
Controller Filters: These apply to all actions within a specific controller.
Action Filters: These apply to only a specific action method.
The way a filter works is that when a request comes into ASP.NET Core, it's handled by the Middleware first, then passed on to the MVC framework. When MVC receives it, the filters are applied in the order of Authorization, Resource, Action, Exception, and Result.
Remember, filters can modify the request and the response. They are executed in the order they are added, and they also have the ability to short-circuit the rest of the pipeline. For example, an Authorization filter can stop further processing if the user is not authorized.
That's a high-level overview of filters in ASP.NET Core! They provide a rich architecture for managing cross-cutting concerns and customizing the behavior of your ASP.NET Core application. They can make your code cleaner and easier to maintain by consolidating these common behaviors in one place, instead of scattering throughout your controllers and actions.
Before you go crazy and start implementing them, please consider the below:
1) They are supposed to be light-weighted! They run with every single request, so do not implement heavy-duty logic! Consider alternatives!
2) They are not replacements for design patterns like CQRS etc. They have a good reason to exist in an API, but remember to keep a separation of concerns!
3) All things are in consideration! Even if they are lightweight, having too many of them, will slow down your application eventually!
Files you can download: