ASP.NET How to use core MVC filter

Time:2021-4-22

The function of the filter is to do some processing before or after the execution of the action method. Use filters to avoid duplicate code for action methods. For example, you can use exception filters to merge exception handling code.

How does the filter work?

The filter runs in the MVC action call pipeline, sometimes called the filter pipeline. MVC selects the action method to be executed before executing the filter pipeline

realization

The filter supports both synchronous and asynchronous interface definitions. Depending on the type of task performed, you can choose whether to implement it synchronously or asynchronously.

Synchronization filters define onstage executing and onstage executed methods, which run code before and after a specific phase of the pipeline. for exampleIActionFilterFilter is called before calling the Action method.OnActionExecutingAfter the Action method is returned, it is called.OnActionExecuted


 public class SampleActionFilter : IActionFilter
 {
  public void OnActionExecuting(ActionExecutingContext context)
  {
   // do something before the action executes
  }

  public void OnActionExecuted(ActionExecutedContext context)
  {
   // do something after the action executes
  }
 }

The asynchronous filter defines an onstage execution async method. This method provides a delegate of filtertypeexecutiondelegate, which will perform the work of specific pipeline phase when called. For example,ActionExecutionDelegateUsed to call the action method, which you can execute before and after.


 public class SampleAsyncActionFilter : IAsyncActionFilter
 {
  public async Task OnActionExecutionAsync(
   ActionExecutingContext context,
   ActionExecutionDelegate next)
  {
   // do something before the action executes
   await next();
   // do something after the action executes
  }
 }

You can implement multiple filter interfaces in a single class. For example,ActionFilterAttributeAbstract classes implement iactionfilter and iresultfilter, as well as their corresponding asynchronous interfaces.

Tips

You don’t need to implement both filter interfaces simultaneously, either synchronously or asynchronously. The framework first checks whether the filter implements an asynchronous interface, and if so, executes the asynchronous method directly. If not, it executes the method of the synchronization interface. If both interfaces are implemented on a class, only asynchronous methods are called. When using abstract classes like actionfilterattribute, you only need to override the synchronous or asynchronous methods of the filter.

Filter type

ASP.NET The core has the following five types of filters, each of which is executed at different stages in the filter pipeline:

1.Authorization Filter

The authorization filter is executed first in the filter pipeline. It is usually used to verify the validity of the current request. If it is illegal, the subsequent pipeline will skip directly. They have only one before method, unlike most other filters that support both pre phase and post phase methods. Note that you do not throw exceptions in the authorization filter because there is no code to handle them (the exception filter does not handle them).

2.Resource Filter

The resource filter is the second run, executed after the authorization filter and before the model binding. In terms of performance, resource filters are particularly important in implementing caching or truncating filter pipelines.

3.Action Filter

The most used filter executes code before and after calling the acioin method. Similar to resource filter, but model binding is executed later.

4.Exception Filter

Used to execute exception handling policies for applications.

5.Result Filter

When the action is finished, the filter will be executed at last. It is used to process the output policy of actionresult.

Filter operation sequence

ASP.NET Each request of the core will go through the registered middleware first, and then the filter will be executed: the same type of filter will be executed in the way of first in, last out.

The yellow arrow is the normal flow
The gray arrow is the exception handling flow

Scope and execution order of filters

Filters have three different levels of scope. You can register the filter to the specified controller or action method through attribute; you can also register the filter to the specified controller in the configureservices method of the startup class MvcOptions.Filters As a global filter for all controllers and action methods:


 public class Startup
 {
  public void ConfigureServices(IServiceCollection services)
  {
   services.AddMvc(options =>
   {
    options.Filters.Add(new AddHeaderAttribute("GlobalAddHeader", 
     "Result filter added to MvcOptions.Filters")); // an instance
    options.Filters.Add(typeof(SampleActionFilter)); // by type
    options.Filters.Add(new SampleGlobalActionFilter()); // an instance
   });

   services.AddScoped<AddHeaderFilterWithDi>();
  }
 }

Examples come fromASP.NET Core MVC English document

Default execution order

When there are multiple filters in a certain stage of the pipeline, the default order of filter execution is determined by the scope: the global filter takes precedence over the controller filter, and the controller filter takes precedence over the action method filter.

The following example is the order of synchronous action filter calls:

Serial number Filter scope Filter method
1 Global OnActionExecuting
2 Controller OnActionExecuting
3 Method OnActionExecuting
4 Method OnActionExecuted
5 Controller OnActionExecuted
6 Global OnActionExecuted

Tips

The base class of each controller contains onactionexecuting and onactionexecuted methods. Where OnActionExecuting is called before all filters, and OnActionExecuted is called after all filters.

Override default execution order

You can override the default execution order by implementing the iorderedfilter interface. This interface exposes that the order property represents the priority to determine the order of execution; a filter with a lower order value will execute the pre method before a filter with a higher order value; a filter with a lower order value will execute the post method after a filter with a higher order value.

You can use the constructor parameter to set the order property:


[MyFilter(Name = "Controller Level Attribute", Order=1)]

If you set the order of the action filter in the above example to 1 and the order properties of the controller and global filter to 2 and 3, respectively, the execution order will be the reverse of the default.

Serial number Filter scope Order property Filter method
1 Method 1 OnActionExecuting
2 Controller 2 OnActionExecuting
3 Global 3 OnActionExecuting
4 Global 3 OnActionExecuted
5 Controller 2 OnActionExecuted
6 Method 1 OnActionExecuted

When the filter is executed, the order property takes precedence over the scope. The filters are sorted first by the order property and then by the scope. All built-in filters implement the iorderedfilter interface and set the order value to 0 by default; therefore, unless the order property is set to a non-zero value, it is executed according to the priority of the scope.

summary

Today we have learned about the basic knowledge of filters. In the next blog, we will introduce the knowledge of built-in filters, the use of filters, dependency injection, cancellation and truncation. Thank you!

The above is the whole content of this article, I hope to help you learn, and I hope you can support developer more.