Action Filters in .NET Core
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 interface
- It will ask you to implement those two methods OnActionExecuted and OnActionExecuting
- 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
public class GlobalFilter : IActionFilter
{
public void OnActionExecuted(ActionExecutedContext context)
{
Console.WriteLine("Global Action Executed");
}
public void OnActionExecuting(ActionExecutingContext context)
{
Console.WriteLine("Global Action is Executing");
}
}
// Add services to the container.
builder.Services.AddControllers(options =>
{
options.Filters.Add(new GlobalFilter());
});
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.
public class NewsletterFilter : IActionFilter
{
public void OnActionExecuted(ActionExecutedContext context)
{
Console.WriteLine("Action Executed");
}
public void OnActionExecuting(ActionExecutingContext context)
{
Console.WriteLine("Action is Executing");
}
}
// Add it in Program.cs
builder.Services.AddScoped<NewsletterFilter>();
// Use this on your controller
[ServiceFilter(typeof(NewsletterFilter))]
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
// Your controller actions go here...
}
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 of IActionFilter it has an extra method OnActionExecutionAsync which takes action context and delegate in parameters
-
For more details you can read here
Whenever you're ready, there are 3 ways I can help you:
- Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
- Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
- Patreon community : Get access to all of my blogs and articles at one place