How to use filters in ASP.NET Core MVC

Take advantage of filters to execute custom code at specific points in the request processing pipeline and avoid code duplication across actions.

How to use filters in ASP.NET Core MVC
Thinkstock

Filters allow you to run code at certain stages of the request processing pipeline. In other words, we may run code before or after certain phases of the request processing pipeline by using filters in ASP.NET Core MVC 5.

ASP.NET Core MVC contains many built-in filters. Since each filter has a distinct purpose, they are executed at different stages in the filter pipeline. The different types of filters correspond to the various pipeline stages, from authorization to execution of results. In addition to built-in filters for authorization, exception handling, etc., you can also write your own custom filters.

This article discusses the types of filters available in ASP.NET Core 5 and how we can work with them in our applications. To work with the code examples provided in this article, you should have Visual Studio 2019 installed in your system. If you don’t already have a copy, you can download Visual Studio 2019 here.

Create an ASP.NET Core MVC project in Visual Studio 2019

First off, let’s create an ASP.NET Core project in Visual Studio 2019. Following these steps to create a new ASP.NET Core MVC 5 project in Visual Studio 2019.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “ASP.NET Core Web App (Model-View-Controller)” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window, specify the name and location for the new project.
  6. Optionally check the “Place solution and project in the same directory” check box, depending on your preferences.
  7. Click Next.
  8. In the “Additional Information” window shown next, select .NET 5.0 as the target framework from the drop-down list at the top. Leave the “Authentication Type” as “None” (default).
  9. Ensure that the check boxes “Enable Docker,” “Configure for HTTPS,” and “Enable Razor runtime compilation” are unchecked as we won’t be using any of those features here.
  10. Click Create.

We’ll use this new ASP.NET Core MVC 5 project to work with filters in the subsequent sections of this article.

Action filters in ASP.NET Core MVC

Action filters are invoked both before and after the execution of an action method. You can use custom action filters to execute reusable code before or after an action method is executed.

You can build a custom action filter by extending the IActionFilter interface and implementing its members. With the help of the sample code provided below, you can create a simple custom action filter in ASP.NET Core MVC 5.

public class CustomActionFilter : IActionFilter
    {
        public void OnActionExecuting(ActionExecutingContext context)
        {
            // Executed before execution of an action method
        }
        public void OnActionExecuted(ActionExecutedContext context)
        {
            // Executed after execution of an action method
        }
    }

Here’s the async version of the above custom action filter for your reference:

public class CustomActionFilter : IAsyncActionFilter
    {
        public async Task OnActionExecutionAsync(ActionExecutingContext
        context, ActionExecutionDelegate next)
        {
            //Executed before execution of an action method
            await next();
            //Executed after execution of an action method
        }
    }

The following code snippet illustrates how you can register the custom action filter.

public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers(config =>
            {
                config.Filters.Add(new CustomActionFilter());
            });
            services.AddControllersWithViews();
        }

You can read more about using action filters in ASP.NET Core MVC in my earlier article here.

Authorization filters in ASP.NET Core MVC

Authorization filters are executed at the beginning of the request pipeline, before any other filters have been executed. They are used to verify a user’s credentials in order to identify whether or not the user is allowed to access the resource.

The following code snippet illustrates how you can implement a custom authorization filter.

public class AuthorizeActionFilter : IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationFilterContext context)
        {
           //Write you code here to authorize or unauthorize the user
        }
    }

The next code snippet illustrates how you can implement a custom authorization filter that can be used to restrict access to an action method or a controller.

public class CustomHttpsOnlyFilter : Attribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            if (!context.HttpContext.Request.IsHttps)
               context.Result = new ForbidResult();
        }
    }

And the next code snippet shows how you can use this custom authorization filter on an action method.

public class HomeController : Controller
    {
        [CustomHttpsOnlyFilter]
        public string Index()
        {
            return "Hello World!";
        }
    }

Resource filters in ASP.NET Core MVC

Resource filters are executed immediately after authorization, i.e., directly after the authorization filter has been executed. You can take advantage of a resource filter to implement caching or to short-circuit the filter pipeline.

The following code snippet illustrates how you can implement a resource filter by extending the IResourceFilter interface and then implementing the OnResourceExecuting and OnResourceExecuted methods.

public class CustomResourceFilterAttribute : Attribute, IResourceFilter
{
    public void OnResourceExecuting(ResourceExecutingContext context)
    {
        context.Result = new ContentResult()
        {
            Content = "This is a Resource filter."
        };
    }
    public void OnResourceExecuted(ResourceExecutedContext context)
    {
    }
}

Result filters in ASP.NET Core MVC

In ASP.NET Core MVC, result filters are executed before or after action filters are executed in the filter pipeline. You can create your own result filter class by extending the IResultFilter or IAsyncResultFilter interface.

The IResultFilter interface comprises two method declarations, i.e., OnResultExecuting and OnResultExecuted. While the former is called before the result from an action method has been processed, the latter is called immediately after the result from an action method has been processed.

The following code snippet illustrates how a custom result filter can be implemented.

public class CustomResultFilter : Attribute, IResultFilter
    {
        public void OnResultExecuting(ResultExecutingContext context)
        {
            context.Result = new ViewResult
            {
                ViewName = "Hello"
            };
        }
         public void OnResultExecuted(ResultExecutedContext context)
        {
        }
    }

To give the above code a try, create a view named Hello in the Views\Shared folder. You can write the following code in your controller class to see the result filter in action.

[CustomResultFilter]
public ViewResult Index() => View();

When you execute the application, the newly created view will be displayed in the web browser.

Exception filters in ASP.NET Core MVC

Exception filters are used to deal with any exceptions that may arise throughout the pipeline. You can leverage exception filters to apply global policies to unhandled exceptions in your application and to execute custom code when an exception has occurred.

To build an exception filter, create a class that inherits from the IExceptionFilter interface and implements each of its members. If you want to create your own custom exception filter, you can do so by extending the abstract class named ExceptionFilterAttribute and overriding the OnException method of that class. Remember that the abstract class ExceptionFilterAttribute implements the IExceptionFilter interface.

The following code sample demonstrates how to build a custom exception filter class by extending the IExceptionFilter interface and implementing its OnException method.

public class CustomExceptionFilter : Attribute, IExceptionFilter
    {
        public void OnException(ExceptionContext context)
        {
            context.Result = new ViewResult()
            {
                StatusCode = (int)HttpStatusCode.BadRequest,
                ViewName = "Error"
            };
            context.ExceptionHandled = true;
        }
    }

Filters in ASP.NET Core MVC allow you to run custom code before or after a certain point in the request processing pipeline and avoid duplication of code across actions. Note that you can define the order in which the filters in the HTTP request pipeline should be executed, and you can implement async versions of each of the filters demonstrated here. I’ll discuss these and other advanced features of filters in a later post here.

Copyright © 2021 IDG Communications, Inc.

How to choose a low-code development platform