Filters come in handy when we wish to build cross-cutting concepts in the MVC stack of ASP.NET Core. They are useful when we wish to implement features such as authorization or caching. ASP.NET Core provides some out-of-the-box filter types. Each of these can be used for a specific purpose in our service:
Filter type | Type description |
Authorization |
This kind of filter is related to the authorization of users. It is the first filter that's executed in the filter pipeline and can short-circuit the pipeline of requests. |
Resource |
Resource filters run immediately after authorization filters and after the rest of the pipeline has completed. They're useful when we wish to implement caching or for performance implementations. |
Action |
Action filters are focused on the life cycle of action methods. They intercept and change the arguments and the returning results of action methods. |
Exception |
Exception filters are used to intercept and apply cross-cutting policies to unhandled exceptions. |
Result |
Result filters are executed immediately before and after the execution of an action result. They are usually implemented to change the formatting of the outcome. It is essential to note that they are executed only when the action method is completed successfully. |
The following diagram shows the workflow of different types of action filters in a request-response workflow:
As you can see, in a request-response pipeline, different types of filters act at various stages. Authorization filters act before everything else and block the requests in the event any of the privileges are wrong. Resource filters operate before model validation and model binding of the request and also when the results of our request come back from the server. The action filter type acts before and after an action's invocation. Furthermore, if an action throws an exception, the exception filter is triggered. At the end of the pipeline, the result filter operates on the IActionResult final object instance. Now that we know about the different filter types that are provided by ASP.NET Core, we will look at some concrete implementation examples.