Browse Tutorials
Exploring ASP.NET Core Filters

Exploring ASP.NET Core Filters

01 Apr 2024
Advanced
44.1K Views
20 min read

ASP.NET Core Filters: An Overview

In Asp.Net Core applications, Controllers have action strategies and methodologies that operate once any user interacts with the interface. If the user clicks on any button the corresponding action methodology is dead. However, this action methodology does not die directly. It's to be passed in many steps. That means, it follows the route - once the user clicks on the button, the request is routed to seek out the Controller and also the corresponding action methodology is named. In this tutorial, we'll get to know What are Filters in .NET Core?, Types of Filters with examples and much more.

Join our ASP.NET Core Certification Training, where your coding journey transforms into a remarkable tech adventure. Embrace the power of problem-solving and enroll today.

Read More: Top 50 ASP.NET Interview Questions and Answers

What are Filters in .NET Core?

If we would like to perform any operation before or once the action methodology is named, we've to have faith in filters. As a result, filters are used for performing arts pre- and post-logic before and once the action methodology gets dead. ASP.NET Core comes with a thought of filters. Filters intercept the stages of the MVC pipeline and permit us to run code before/after their execution.

Process Flow Of Filters

Filters run among the ASP.Net Core action invocation pipeline also referred to as the filter pipeline. The filter pipeline runs when ASP.Net Core selects the action to execute. So, when a filter is executed within the pipeline, there are always different scenarios for every execution. So, before creating a filter, we first analyze our requirements so that we can decide which filters we require exactly and in which position of the filter pipeline for executions. In Asp.Net Core, the filter always executes from the MVC Action method which is known as the Filter Pipeline and it will be executed when the action method is executed.

Different filter kinds run at all completely different points along the pipeline. In the filter pipeline, some filters are executed before the execution of the next level like Authorization filters. Also, some filters are executed before and after the state of execution in the filter pipeline. Action filters are one of the examples of these types of filters.

Process Flow Of Filters

Read More: Salary Offered to ASP.NET Developers

Types Of Filters

In Asp.Net Core, filter execution depends on the MVC Action pipeline. Normally, the filter pipeline is executed when any action of the MVC Controller needs to be executed or execution is already done. There are different types of filters in the Asp.Net Core. Below are the different filter types and their importance in the process flow.

Authorization Filters

The Authorization filters performance measure dead initial. This filter helps us to work out whether or not the user is allowed for the present request. If a user is not authorized for the request, then this filter will break the pipeline process flow. We can additionally produce a custom authorization filter.

[Authorize]
public IActionResult MyAction()
{
    // Action logic
}    

Resource Filters

The Resource filters handle the authorized request in the process flow. This filter can execute before and after the process flow in the filter execution. Normally, this type of filter activates before the model data binding at the controller level. For example, OnResourceExecuting runs code before model binding. This filter can be used for caching implementations. IResourceFilter or IAsyncResourceFilter interfaces are implemented by this filter.

public class MyResourceFilter : IResourceFilter
{
    public void OnResourceExecuting(ResourceExecutingContext context)
    {
        // Before action execution
    }

    public void OnResourceExecuted(ResourceExecutedContext context)
    {
        // After action execution
    }
}    

Action Filters

If we want to execute the filter code instantly with the controller action method, we need to use the Action filters. We can use the action filter before or after the execution of any controller action method. We can additionally manipulate the arguments passed into Associate in Nursing action. Action filters normally implement the IActionFilter interface or IAsyncActionFilter interface.

public class MyActionFilter : IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext context)
    {
        // Before action execution
    }

    public void OnActionExecuted(ActionExecutedContext context)
    {
        // After action execution
    }
}    

Exception Filters

If we want to track any type of exception at the time of code execution and then return that exception message to the process from where a request has been raised, we need to use Exception filters. These types of filters can be implemented with the help of the IExceptionFilter or IAsyncExceptionFilter interface. This type of filter is normally used to handle common error-trapping messages or logging in any application.

public class MyExceptionFilter : IExceptionFilter
{
    public void OnException(ExceptionContext context)
    {
        // Exception handling logic
    }
}    

Result Filters

If we want to track the result of any controller action method then we need to use the Result filter. They're dead given that the controller action technique has been dead with success. With the help of the IResultFilter or IAsyncResultFilter interface, we can define the Result filters.

public class MyResultFilter : IResultFilter
{
    public void OnResultExecuting(ResultExecutingContext context)
    {
        // Before result execution
    }

    public void OnResultExecuted(ResultExecutedContext context)
    {
        // After result execution
    }
}    

The below image demonstrates the process flow including execution flow in Asp.Net Core –

 execution flow in Asp.Net Core

Implementation of Filters in ASP.NET Core

We can implement filters in two different ways.

  1. Synchronous filters: They normally execute the code before the execution of the action methods OnStageExecuting and OnStageExecuted. An example of the Synchronous filter is ActionFilter. The OnActionExecuting is called before the action method is called and OnActionExecuted after the action method returns.
    namespace CoreDemoSamples.Filters
    {
     public class MyActionFilter : IActionFilter
     {
     public void OnActionExecuting(ActionExecutingContext objContext)
     { 
     }
    
     public void OnActionExecuted(ActionExecutedContext objContext)
     { 
     }
     }
    }
    
  2. Asynchronous filters: It defines an OnStageExecutionAsync methodology. This type of filter method execution always depends on the FilterTypeExecutionDelegate delegate. As demonstrated in the below code, the ActionExecutionDelegate parameter is responsible for the execution call of the next filter action. Also, we can execute the action method code before the filter executions.
    namespace CoreDemoSamples.Filters
    {
     public class CustomAsyncActionFilter : IAsyncActionFilter
     {
     public async Task OnActionExecutionAsync(
     ActionExecutingContext objContext,
     ActionExecutionDelegate objNext)
     { 
     }
     }
    }
    

Multiple Filter Stages

Interfaces for multiple filter stages can be implemented in a single class. For example, the ActionFilterAttribute class implements:

  • Synchronous: IActionFilter and IResultFilter
  • Asynchronous: IAsyncActionFilter and IAsyncResultFilter
  • IOrderedFilter

Implement either the synchronous or the async version of a filter interface, not both. The runtime checks first to see if the filter implements the async interface, and if so, it calls that. If not, it calls the synchronous interface's method(s). If both asynchronous and synchronous interfaces are implemented in one class, only the async method is called. When using abstract classes like ActionFilterAttribute, override only the synchronous methods or the asynchronous methods for each filter type.

Filter Scopes and Order of Execution

In Asp.Net Core, the filters are often side to the pipeline at one in every of three different scopes

  1. by action methodology
  2. by controller category
  3. By global declaration means we can use or apply those filters either at the controller level, action method level, or both.

If we want to register the filters, then we can define those within the ConfigureServices method with the help MvcOption.Filters.

public void ConfigureServices(IServiceCollection objServices) 
{ 
 objServices.AddMvc(options=> { 
 //an instant 
 options.Filters.Add(new MyActionFilter()); 
 //By the type 
 options.Filters.Add(typeof(MyActionFilter)); 
 }); 
} 

When multiple filter area units are applied to the actual stage of the pipeline, the scope of the filter defines the default order of the filter execution. In the filter process flow, the first global level filter is executed first, then it is executed the controller level filters and at last, it will execute the action method level filters. The below image displays the filter process execution order.

filter process execution order

If we want to override the process execution order of the filter, then we can perform that with the help IOrderedFilter interface. This interface has the property named Orderwhich is used to work out the order of execution. In this case, the process flow normally executes the filters in ascending order means from lower order to higher order. We will set up the order property exploitation of the creator parameter.

public class DemoFilterAttribute : Attribute, IActionFilter, IOrderedFilter 
 { 
 public int SequenceNo { get; set; } 
 public void OnActionExecuting(ActionExecutingContext objContext) 
 { 
 //before the action executes 
 } 
 public void OnActionExecuted(ActionExecutedContext objContext) 
 { 
 //after the action executes 
 } 
 } 

Now, this DemoFilterAttribute can be applied in the controller action method as below –

[DemoFilter(SequenceNo = 1)] 
public class UserController : BaseController 
{ 
 public IActionResult HomeIndex() 
 { 
 return View(); 
 } 
}

In the normal scenario, the order sequence of all the inbuilt filters is 0. If we want to create any custom filter, then the order sequence of that filter must start from 1. Because, at the execution time, it will soften the filter list based on Order and then start execution as per the sorted filter list.

Filter Dependency Injection

Filters will be added by sort or by instance. In the case of the instance, each request is used for this instance. If you add a sort, it'll be type-activated, which means an instance is created for every request and any constructor dependencies are inhabited by dependency injection (DI). Adding a filter by sort is equivalent to the constructor of a class. Filters that area unit enforced as attributes and add on to controller categories or action ways cannot have builder dependencies provided by dependency injection (DI).

If we develop some filters that contain dependency, then we need to use that dependency with the help of dependency injection. You can apply your filter to a category or action methodology victimization one in every of the following

  1. ServiceFilterAttribute
  2. TypeFilterAttribute
  3. IFilterFactory

In the case of ServiceFilter, we can filter instances with the help of Dependency Injection. To activate this filter, we first need to add this filter with the help of ConfigureService and then, we can use the reference of this filter either in the controller class or action method as a ServiceFilter. One of the dependencies we would need to urge from the DI could be a faller among filters, we would log one thing happened. An example is an action filter with faller dependency.

public class DemoFilterForDI : IActionFilter 
{ 
 private ILogger _objLogger; 
 public DemoFilterForDI(ILoggerFactory objFactory) 
 { 
 _objLogger = objFactory.CreateLogger<DemoFilterForDI>(); 
 } 
 public void OnActionExecuting(ActionExecutingContext objContext) 
 { 
 //before the action executes 
 _objLogger.LogInformation("OnActionExecuting"); 
 } 
 public void OnActionExecuted(ActionExecutedContext objContext) 
 { 
 //after the action executes 
 _objLogger.LogInformation("OnActionExecuted"); 
 } 
}

Now, register this filter in the configuration service method as below

public void ConfigureServices(IServiceCollection objService) 
{ 
 objService.AddScoped<DemoFilterForDI>(); 
}

Now, use the above service filter in the action method of the controller

[ServiceFilter(typeof(DemoFilterForDI))] 
public IActionResult Index() 
{ 
 return View(); 
}

It is a terrible kind of ServiceFilterAttribute and conjointly enforced from the IFilterFactory interface. In this case, it does resolve directly from the dependency injection, but it initializes the type with the help of "Microsoft.Extensions.DependencyInjection.ObjectFactory". Due to this difference, we need to register types within the ConfigureService method which are already referenced in TypeFilterAttribute.

The TypeFilterAttribute will optionally settle for builder arguments for the sort. The following example demonstrates the way to pass arguments to a sort victimization TypeFilterAttribute.

[TypeFilter(typeof(DemoFilterAttribute), Arguments = new object)] 
public IActionResult AboutIndex() 
{ 
 return View(); 
}

Security Considerations with Filters

Security is always a major concern even while you're working with filters in ASP.NET Core so as to make sure that all your sensitive data stays protected and there is proper authorization and authentication.

A. Preventing Overuse of Filters

  • Overuse of filters may increase the chances of decrease in performance and can also lead to attack surface.
  • To avoid unnecessary processing, try to apply filters only where they are really required, if not then avoid using them.
  • If we put multiple filters for the same action, they can lead to redundancy resulting in unpredictable behavior and unnecessary security risks.

B. Ensuring Proper Authorization and Authentication Checks

  • It is advised to always make sure that there is proper authorization and authentication done.
  • You can authorization filters to make sure that all the sensitive data is protected to prevent it from unauthorized access.
  • Implementing authentication logic along with filters will help in verifying the identities of the users that are trying to access the protected resources.

C. Handling Sensitive Data in Filters

  • You should always perform data validation and sanitization so as to prevent vulnerabilities such as injection attacks whenever filters interact with user input.
  • Using encryption techniques in both transit and at rest will make sure that all the sensitive data stays protected and confidential.
  • You should hardcoding sensitive information like API keys, they can be stored securely in environment variables or encrypted configuration stores.
Summary

The filters enable us to run code before or once bound stages within the request process pipeline. In this article, we discuss the process flow of filters, different types of filters, how it is executed, etc. Also, discussed the ordering of filters, filter scope, how to cancel the request from the filter, and how to implement dependency injection using filters. Enroll yourself In the Best Online ASP.NET Core Coursefrom ScholarHat and Start Your Tech Career the Right Way!

FAQs

Q1. How filters work in ASP.NET Core?

Filters run within the ASP.NET Core action invocation pipeline sometimes referred to as the filter pipeline. The filter pipeline runs after ASP.NET Core selects the action to execute

Q2. What is the other name of invocation pipeline?

It is also referred to as the filter pipeline.

Q3. When Action filters execute?

It runs immediately before and after an action method is called.

Q4. How many types of filters are there in asp .net core?

There are 5 types of filters in ASP.NET Core:
  1. Authorization filters
  2. Resource filters
  3. Action filters
  4. Exception filters
  5. Result filters

Q5. How can I control the order of execution for multiple filters in ASP.NET Core?

To control the order of execution for multiple filters in ASP.NET Core, you can specify it with the help of 'Order' property of the filter attribute or 'IOrderedFilter' interface.

Take our free aspnet skill challenge to evaluate your skill

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

GET CHALLENGE

Share Article
Batches Schedule
About Author
Debasis Saha (Technical Manager, Author and Mentor)

He is an ASP.Net, MVC and Angular Technical Manager with 10 years of experience. He always been a great fan of Microsoft Technologies and loves working on them. He has expertise in Asp.Net, MVC, SQL Server, MongoDB, Angular JS, and Angular. He loves to write articles about these technologies.
Accept cookies & close this