Introduction to ASP. NET Core MVC filter, coremvc

Source: Internet
Author: User

Introduction to ASP. NET Core MVC filter, coremvc

The role of a filter is to perform processing before or after the Action method is executed. Use a filter to avoid repeated code of the Action method. For example, you can use an exception filter to merge the code for exception handling.

How does a filter work?

Filters run in the MVC Action call pipeline, which is sometimes called a filter pipeline. After MVC selects the Action method to be executed, the filter pipeline will be executed:

Implementation

Filters support synchronous and asynchronous interface definitions at the same time. You can select synchronous or asynchronous implementation based on the task type.

The synchronization filter defines the OnStageExecuting and OnStageExecuted methods, and runs the code before and after a specific stage of the pipeline. For exampleIActionFilterFilter, called before calling the Action MethodOnActionExecuting, Called after the return of the Action MethodOnActionExecuted:

 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 OnStageExecutionAsync method. This method provides the FilterTypeExecutionDelegate delegate. When this delegate is called, the pipeline stage is executed. For example,ActionExecutionDelegateIt is used to call the Action method. You can execute code before and after calling it.

 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, the ActionFilterAttribute abstract class implements IActionFilter and IResultFilter, and Their Asynchronous interfaces.

Prompt

You do not need to implement two filter interfaces simultaneously, either synchronous or asynchronous. The framework first checks whether the filter implements an asynchronous interface. If yes, it directly executes the Asynchronous Method. If not, it executes the synchronous interface method. If two interfaces are implemented simultaneously in a class, only asynchronous methods are called. When using abstract classes such as ActionFilterAttribute, you only need to overwrite the synchronous or asynchronous methods of the filter.

Filter Type

ASP. NET 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 the first execution in the filter pipeline. It is usually used to verify the validity of the current request. If it is invalid, the pipeline will skip it directly. They only have one Before method, unlike most other filters that support the pre-stage method and post-stage method. Note: Do not throw exceptions in the authorization filter because no code is available to handle exceptions (the exception filter does not process them ).

2. Resource Filter

The resource Filter is the second operation. It is executed after Authorization Filter and before Model Binding. In terms of performance, resource filters are particularly important in implementing caching or Intercepting Filter pipelines.

3. Action Filter

The filter with the highest usage rate executes code before and after the Acioin method is called. It is similar to Resource Filter, but Model Binding is executed later.

4. Exception Filter

Used to execute exception handling policies for applications.

5. Result Filter

After the Action is executed, the filter is executed. It is used to process the output policy of ActionResult results.

Filter running sequence

Each request of ASP. NET Core first passes through the registered Middleware, and then the filter will be executed: the same type of filter will be executed in an advanced and later manner.

The colored arrow is normal.
The gray arrow shows the exception handling process.

Scope and execution sequence of filters

Filters have three levels of scopes. You can use Attribute to register a filter to a specified controller or Action method. You can also register a filter to MvcOptions in the ConfigureServices method of the Startup class. set of Filters as a global filter (valid 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>();  } }

The example is from the ASP. NET Core MVC English document.

Default execution sequence

When multiple filters exist in a stage of the pipeline, the default sequence 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 shows the sequence 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

Prompt

Each Controller's base class Controller contains the OnActionExecuting and OnActionExecuted methods. OnActionExecuting is called before all filters, and OnActionExecuted is called after all filters.

Overwrite the default execution sequence

You can override the default execution sequence by implementing the IOrderedFilter interface. This interface exposes the Order attribute to indicate priority to determine the execution Order. Filters with lower Order values will execute the pre-method before filters with higher Order values; 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 parameters to set the Order attribute:

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

If you set the Order of the Action filter to 1 in the preceding example and set the Order attribute of the controller and global filter to 2 and 3 respectively, the execution Order is the opposite to the default one.

Serial number Filter scope Order attribute 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 priority of the Order attribute is higher than that of the scope. The filter is first sorted by the Order attribute 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 attribute is set to a non-zero value, it is executed based on the priority of the scope.

Summary

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

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.