→ Filters and Their Benefits ?
→ Types of Filters ?
→ Action Filters ?
Filters and Their Benefits ?
Filters gives us the facility to run a piece of code before or after any stage in request processing pipeline. You are already familiar with filters , let me remind you , you would have used authorization (attribute Authorized) it basically applies filter on your actions and checks is it authorized or not so that is a filter.
Filters have many benefits here are few
Reusability - Instead of writing code for each action we write it one time and then use it
Extensible : They give use facility to do some ABC action before method and some XYZ operation after that method
Types of Filters ?
We commonly use five types of filters in our applications in same order as they run
Authorization Filters : Top most in running order to check is user authorized.
Resource Filters : It runs after authorization and before other request pipeline.
Action Filters : It runs before and after an action method is called
Exception Filters : It is used to handle global exceptions , it gets executed when an unhandled exception occurs.
Result Filters : It runs when action method has been excecated , and then before and after execution of action results.
Action Filters
Action filters run immediately before and after an action method is called. It can do couple of things e.g. changing the passed arguments and changing the results.
Today we will see two implementations of action filters
Global
Custom Action Based
Following steps are same for both
Create your filter by inheriting class from
IActionFilter
interfaceIt will ask you to implement those two methods
OnActionExecuted
andOnActionExecuting
OnActionExecuted runs after the method and other one before the method gets called.
Global Action Filter
After creating that filter you need to add it in services container for controllers.
That’s all you need to do it so this one will run whenever any action gets called
Custom Action Based Filter
Add your filter in Program.cs , if you have multiple filters add in similar fashion.
Add
ServiceFilter(typeof(YourFilter))
at your controller level or action level , that’s all.
When I applied Global Action Filter and Newsletter (Custom Filters) on same controller it executed like this
Some Key Points
If you want asynchronous action filter then you can inherit from
IAsyncActionFilter
instead ofIActionFilter
it has an extra methodOnActionExecutionAsync
which takes action context and delegate in parametersFor more details you can read here
Whenever you’re ready , there are 3 ways I can help you
Promote yourself to 2100+ subscribers by sponsoring my Newsletter (Reach me at mwaseemzakir@gmail.com)
Become a Patron and get access to 100+ .NET Questions and Answers
Get my FREE eBook from Gumroad that contains 30 .NET Tips (1000+ Downloads)