Filters in ASP.NET Core

Filters in ASP.NET Core

In ASP.NET core world , a user request is routed to appropriate controller and then action method to be executed. In some cases, user may need to run some code before or after during execution pipeline.

Filters allows some code to run before and after specific stage in request processing pipeline. ASP.NET core has provided some built in filters , user could also create custom filters as well. Filters can also avoid duplicate code, for example exception filter can consolidate the error handling.

Built in filters are used for authorization, response caching, short circuiting the request processing pipeline.

Custom filters can be used for error handling, caching, configurations and logging purposes.

Filter pipeline runs after ASP.NET Core selects the action to be executed.

image.png

Filter types

Authorization Filter

Authorization filter is executed at the beginning of the request processing pipeline. This filter is used to determine whether user is authorized for request, and if not request pipeline can be short circuited.

    public class AuthorizationFilter : Attribute, IAuthorizationFilter {
        public void OnAuthorization(AuthorizationFilterContext context) {
            context.HttpContext.Response.WriteAsync("  OnAuthorization  ==> ");
        }
    }

Resource Filter

Resource filter is executed just after Authorization filter. This filter can be used to implement response caching, short circuiting the pipeline.

OnResourceExecuting runs code before the model binding. OnResourceExecuted runs after rest of the pipeline is executed.

    public class ResourceFilter : Attribute, IResourceFilter  {
        public void OnResourceExecuted(ResourceExecutedContext context)  {
            context.HttpContext.Response.WriteAsync("  OnResourceExecuted  ==>  ");
        }
        public void OnResourceExecuting(ResourceExecutingContext context) {
            context.HttpContext.Response.WriteAsync("  OnResourceExecuting  ==>  ");
        }
    }

Action Filter

Action filter is executed before and after the execution of action method inside controller. A custom action filter can be used to execute some reusable code block before or after execution of controller action. Action filter can modify the arguments passed into action method or can modify the result returned from action method.

    public class ActionFilter : Attribute, IActionFilter {
        public void OnActionExecuted(ActionExecutedContext context) {
            context.HttpContext.Response.WriteAsync("  OnActionExecuted  ==>  ");
        }
        public void OnActionExecuting(ActionExecutingContext context) {
            context.HttpContext.Response.WriteAsync("  OnActionExecuting  ==>  ");
        }
    }

Exception Filter

Exception filter can be used to handle exception during request processing pipeline. Using this filter, exceptions can be handled globally.

    public class ExceptionFilter : Attribute, IExceptionFilter  {
        public void OnException(ExceptionContext context)  {
            throw new NotImplementedException();
        }
    }

Result Filter

This filter runs immediately before and after the execution of action result. This runs after completion of the action method.

   public class ResultFilter : Attribute, IResultFilter {
        public void OnResultExecuted(ResultExecutedContext context) {
            context.HttpContext.Response.WriteAsync("  OnResultExecuted  ==>  ");
        }
        public void OnResultExecuting(ResultExecutingContext context) {
            context.HttpContext.Response.WriteAsync("  OnResultExecuting  ==>  "); 
        }
    }

Filter Scope

A filter can be added to the pipeline at three levels

  • Controller level

using an attribute, Filter can be added to pipeline

    [AuthorizationFilter]
    [ResourceFilter]
    [ActionFilter]
    [ResultFilter]
    public class HomeController : Controller {
        private readonly ILogger<HomeController> _logger;
        public HomeController(ILogger<HomeController> logger) {
            _logger = logger;
        }
        public IActionResult Index() {
            HttpContext.Response.WriteAsync("  Inside Action ==>");
            return View();
        }
   }
  • Action Level Using an Attribute at action level
        [ActionFilter]
        public IActionResult Index()  {
            HttpContext.Response.WriteAsync("  Inside Action ==>");
            return View();
        }
  • Globally - For all controllers, Actions
        public void ConfigureServices(IServiceCollection services) {
            services.AddControllersWithViews(option => {
                option.Filters.Add<ResourceFilter>();
            });
        }

Did you find this article valuable?

Support Deepak Kumar Jain by becoming a sponsor. Any amount is appreciated!