In ASP.NET MVC, Filters are used to inject logic at different levels of request processing and allow us to share logics across Controllers. For example, let’s say we want to run a security logic or a logging logic across the controller. To do so, we’ll write a filter containing those logics and enable them across all controllers. When we enable a filter across all controllers or actions, the filter enables the upcoming HTTP request.
Let us consider a scenario of Logging: for every incoming request, we need to log some data to the files on the basis of some logic. If we don’t create this logic inside a custom filter, then we will have to write logic for each controller’s action. This mechanism will lead to two problems:
- duplication of code; and
- violation of the Single Responsibility Principles; actions will now perform additional tasks of logging.
We can mitigate the problems above by putting the logging logics inside a custom action filter and applying the filter at all the controllers’ level.
Have you ever come across source code as shown in the image below? [Authorize] is an Authorization filter, and it gets executed before any HTPP request or Action method execution. The Authorize filter is part of MVC, but if needed, we can create a custom filter too.