Filters in ASP.NET MVC
Filters are basically used when we need to perform an action before or after any particular operation.
We can say when we want pre-or post action behavior from an action. ASP.NET MVC provides a feature called the filters.
Now, we can see the types of filters provided by ASP.NET MVC
- Action Filters
- Authorization Filters
- Result Filters
- Exception Filters
Action Filters
Action filters refer to the most general filters in MVC. They are used to implement the logic, which gets executed before or after controller action executes. The name itself defines the work of this filter.
Authorization Filters
This is used to implement authorization and authentication part for any action in the Controller. This checks the access level permission to perform any action in the Controller.
It is basically used to filter the authorized user whether the user has access to the resource or not. The code is given below, which describes an Action method, which is decorated with an Authorize attribute.
Result Filter
Result Filter is the most important filter in MVC. The result filter contains the logic basically and the logic gets executed before or after view result gets executed. Generally, it is very helpful when you want to change the view before it gets rendered to the Browser.
Exception Filter
Exception filters are generally used to handle the error in the Application, may be either caused by controller action or controller action results. Also, this filter is very useful in logging the Application exception.
Other Filters
Output Cache
This filter is generally applied when we want an output of an action for a certain duration. In the code snippet given below, we are decorating an action with an output catche keyword. This will catche the output of an action for 20 seconds.
Handle Error
The name itself defines the filter work. This filter is used when you want to handle the error caused by an Action or a Controller. Let us suppose, if any exception occurs; it redirects the action to custom error page, which we have decorated before or above. Any action, for example in the code given below, will handle an error attribute, which is decorated to an Action method, which is redirected to “error.cshtml” page . When any exception will occur by this action, it will redirect to this particular error page.