Filters in ASP.NET MVC enable you to run code before or after a particular stage in the execution pipeline. They can be configured globally, per controller, or per action. You can consider filters as interceptors.
There are different kinds of filters, and each filter is executed at a different stage in the pipeline. For example, action filters are executed when the action method is executed.
Let us use a simple example to see how an action filter (a type of filter) works.
We've created a simple controller, DateController, where we're just displaying the time. In this action method, we're using a predefined action filter by the name of ResponseCache, that caches the response for the duration specified in seconds. In the following code snippet, we have mentioned the duration as 600 seconds. So, the response will be cached for 10 minutes:
Go to https://goo.gl/pEBqt6 to access the code.
public class DateController : Controller
{
[ResponseCache(Duration = 600)]
public IActionResult Index()
{
return Content(DateTime.Now.ToShortTimeString());
}
}
When we run it for the first time, it displays the time as expected. But when you refresh the browser (which indirectly fires the request again), the time is not updated as the response is cached already by the application.
In the following screenshot, even though the time is 7:43, the application is still showing as 7:40:
Now, we'll look at some of the predefined types of filters available in ASP.NET Core.
Here are some of the different kinds of filters:
- Authorization filters: These are used for authorization and are mainly intended to determine whether the current user is authorized for the request being made.
- Resource filters: These are the filters that handle the request after authorization and are the last ones to handle the request before it leaves the filter pipeline. They are used to implement caching or by passing the filter pipeline.
- Action filters: These wrap calls to individual action method calls and can manipulate the arguments passed in the action as well as the action result returned from it.
- Exception filters: Exception filters are used to manage the unhandled exceptions in ASP.NET MVC.
- Result filters: Result filters wrap the individual action results and they only run when the action method is executed successfully.