Take advantage of action filters in ASP.NET Core MVC to execute custom code at specific points in the request pipeline 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. Launch the Visual Studio 2017 IDE. Click on File > New > Project. Select “ASP.NET Core Web Application (.NET Core)” from the list of templates displayed. Specify a name for the project. Click OK to save the project. A new window, “New .NET Core Web Application…”, will be displayed. Select .NET Core as the runtime and ASP.NET Core 2.1 (or later) from the drop-down list at the top. Select “Web Application (Model-View-Controller)” as the project template. Ensure that the check boxes “Enable Docker Support” and “Configure for HTTPS” are unchecked. We won’t be using these features here. 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. Related content news Wasmer WebAssembly platform now backs iOS Wasmer 5.0 release also features improved performance, a leaner codebase, and discontinued support for the Emscripten toolchain. By Paul Krill Oct 30, 2024 2 mins Mobile Development Web Development Software Development news analysis What Entrust certificate distrust means for developers Secure communications between web browsers and web servers depend on digital certificates backed by certificate authorities. What if the web browsers stop trusting your CA? By Travis Van Oct 30, 2024 9 mins Browser Security Web Development Application Security news Next.js 15 arrives with faster bundler High-performance Rust-based Turbopack bundler moves from beta to stable with the latest update of the React-based web framework. By Paul Krill Oct 24, 2024 2 mins JavaScript React Web Development feature WasmGC and the future of front-end Java development WebAssembly’s garbage collection extension makes it easier to run languages like Java on the front end. Could it be the start of a new era in web development? By Matthew Tyson Oct 16, 2024 10 mins Web Development Software Development Resources Videos