joydip_kanjilal
Contributor

How to use action filters in ASP.NET Core MVC

how-to
Dec 31, 20185 mins
C#Microsoft .NETSoftware Development

Take advantage of action filters in ASP.NET Core MVC to execute custom code at specific points in the request pipeline

2 filtering
Credit: Thinkstock

Filters in ASP.NET Core MVC allow us to execute code before or after specific stages of the request processing pipeline. The different types of filters correspond to the different stages of the pipeline, from authorization to result execution.

For instance, you can leverage action filters in ASP.NET Core MVC to execute custom code before and after the execution of an action method. This article presents a discussion of the built-in filters in ASP.NET Core MVC, why they are useful, and how we can use action filters in our ASP.NET Core applications.

Filters in ASP.NET Core MVC

ASP.NET Core MVC contains many built-in filters. These include the following:

  • ActionFilters. These are executed before and after execution of an action method of a controller. 
  • AuthorizationFilters. These filters are executed at the beginning of the request pipeline. They are used to validate a user’s credentials to check if the user is authorized. 
  • ResourceFilters. These filters are executed after authorization and before model binding occurs. You can take advantage of ResourceFilters to implement caching. 
  • ResultFilters. These filters are used to execute code before and after an action method’s IActionResult is executed. 
  • ExceptionFilters. These filters are used to handle any exceptions that occur in the pipeline. You can take advantage of ExceptionFilters to execute custom code when an exception has occurred. 

The choice of the type of filter to use depends on what you are trying to accomplish. As an example, if you are trying to short-circuit a request (i.e., stop an action method from executing and return a result prematurely), you would use a resource filter. Alternatively, if you are trying to change the action method parameters and the result returned from the action method, you would use an action filter.

The ActionFilterAttribute class implements the IActionFilter, IAsyncActionFilter, IResultFilter, IAsyncResultFilter, and IOrderedFilter interfaces. You can take advantage of this class to implement a method filter, controller filter, or global filter. We’ll examine this later in this article.

Create an ASP.NET Core Web API project in Visual Studio 2017

First off, let’s create an ASP.NET Core Web API project in Visual Studio. If Visual Studio 2017 is up and running in your system, follow the steps below to create an ASP.NET Core MVC project.

  1. Launch the Visual Studio 2017 IDE.
  2. Click on File > New > Project.
  3. Select “ASP.NET Core Web Application (.NET Core)” from the list of templates displayed.
  4. Specify a name for the project.
  5. Click OK to save the project.
  6. A new window, “New .NET Core Web Application…”, will be displayed.
  7. Select .NET Core as the runtime and ASP.NET Core 2.1 (or later) from the drop-down list at the top.
  8. Select “Web Application (Model-View-Controller)” as the project template. 
  9. Ensure that the check boxes “Enable Docker Support” and “Configure for HTTPS” are unchecked. We won’t be using these features here.
  10. Ensure that “No Authentication” is selected. We won’t be using authentication here either. 

This will create a new ASP.NET Core MVC project in Visual Studio. We’ll use this project to implement our action filters in the sections that follow.

Create a custom action filter in ASP.NET Core MVC

You can take advantage of custom action filters to execute reusable code before or after the execution of an action method. You can extend the following abstract base classes to create custom filters. Note that each of these abstract classes extends the Attribute class.

  • ActionFilterAttribute
  • ResultFilterAttribute
  • ExceptionFilterAttribute
  • ServiceFilterAttribute
  • TypeFilterAttribute

You can also extend the IActionFilter interface and implement its methods to create a custom filter. You can create both synchronous and asynchronous filters.

Create a synchronous action filter in ASP.NET Core MVC

The following code snippet illustrates how a synchronous action filter can be created by extending the IActionFilter interface and implementing the OnActionExecuting and OnActionExecuted 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 an asynchronous action filter in ASP.NET Core MVC

To create an asynchronous action filter, you can extend the IAsyncActionFilter interface and implement the OnActionExecutionAsync method as shown in the code snippet below.

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 
        }
    }

Add an action filter in the ConfigureServices method in ASP.NET Core

You can add filters at different levels of scope. These include the action scope, controller scope, and global scope. The following code snippet illustrates how you can add a filter in the global scope. Note how the custom action filter we implemented above is added to the filter collection in the ConfigureServices method of the Startup class. Note that the filter is added to the filter collection by instance.

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

You can also add the filter by type as shown in the code snippet below.

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

Filters enable you to execute code before or after a particular point in the request processing pipeline. One of the great new improvements in action filters in ASP.NET Core MVC is the ability to specify the execution order of the filter in the HTTP request pipeline. We will examine this and many more features of filters in ASP.NET Core MVC in an upcoming post.

joydip_kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author