How to use actionfilter in asp.net core

Time:2021-8-13

Filters in asp.net core MVC allows us toRequest processing pipelineCustom code is executed before and after a certain stage in, and different types of filters correspond toRequest processing pipelineDifferent stages of, for example:ActionFilterYou can execute custom code before or after the action method, which we will discuss in this articleASP.NET Core MVCActionfilter built in, why it is very useful and how to use it in the program.

Filter filter

ActuallyASP.NET Core MVCThere are many built-in filters in, which are generally listed as follows:

  • ActionFilters

It is executed before and after the execution of the action method.

  • AuthorizationFilters

It will be inRequest processing pipelineIs executed at the beginning of, which is mainly used to obtain the user’s informationVoucher informationTo verify whether the user is authorized.

  • ResourceFilters

It will be inauthorizationAfter andModel bindingPreviously executed, it can be used to implement some cache logic.

  • ExceptionFilters

It will captureRequest processing pipelineSo it can be used to implement some custom exception handling.

Which type of filter to use depends on what business you want to implement. For example, if you want toshort circuitRequest, end the pipeline in advance and return the result. Can it be usedResourceFiltersHa, for another example, if you want to modify the input parameters of action and the results of action, actionfilter is your best choice.

Asp.net core MVC has a feature calledActionFilterAttribute, it implements the following interfaces IActionFilter, IAsyncActionFilter, IResultFilter, IAsyncResultFilter, IOrderedFilter, you can use it to implement different levels of filters, such as action level, controller level and global level. We will discuss them one by one later.

Create a custom actionfilter

You can use the custom actionfilter to execute some reusable logic before and after the action method. Perhaps everyone knows that this is the so-called AOP programming, exceptActionFilterAttribute, several other filters have similar attributes.

  • ResultFilterAttribute
  • ExceptionFilterAttribute
  • ServiceFilterAttribute
  • TypeFilterAttribute

In addition to the above quick features, the simplest is to implementIActionFilterInterface can also be implementedsynchronizationandasynchronousDual mode.

Create synchronized actionfilter

The following code snippet shows how to create an actionfilter for synchronous mode and inheritIActionFilterInterface and implement itOnActionExecutingandOnActionExecutedTwo methods.


    public class SimpleActionFilter : IActionFilter
    {
        public void OnActionExecuting(ActionExecutingContext context)
        {
            //this method will be executed before execution of an action method 
        }
        public void OnActionExecuted(ActionExecutedContext context)
        {
            //this method will be executed after an action method has executed 
        }
    }

Create actionfilter for asynchronous mode

The following code snippet shows how to create an actionfilter with asynchronous mode and inheritIAsyncActionFilter Interface and implement itOnActionExecutionAsyncmethod.


    public class SimpleAsyncActionFilter : IAsyncActionFilter
    {
        public async Task OnActionExecutionAsync(ActionExecutingContext context,
          ActionExecutionDelegate next)
        {
            //code written here will be executed before execution of an action method 
            await next();
            //code written here will be executed after execution of an action method 
        }
    }

Configure actionfilter

As mentioned earlier in the article, filter filters can be added to different levels of scopes, including action level, controller level and global level. Here is a demonstration of how to add filters to the global level. Take a closer look at how my custom filter is added to the configureservices methodFilter setIn, the following code is shown:


        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(options =>
            {
                options.Filters.Add(new SimpleAsyncActionFilter());
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

In addition to the above method, you can also usetypeofAdd the method to options, as shown in the following code:


        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(options =>
            {
                options.Filters.Add(typeof(SimpleAsyncActionFilter));
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

To sum up: filters allow us toRequest processing pipelineSome user-defined code is executed before and after a certain point in the. In addition, a very big new improvement of actionfilter is that the execution order of the filter can be specified in the HTTP request pipeline. I will share more advanced features of the filter with you in later articles.

Translation link: https://www.infoworld.com/art…