.Net Core · ASP.NET · C#

Filters – Introduction

In .Net Core, filters are used to run specified block of code in particular stages of request pipeline.
They allow to run the same code across many request, therfore they help to avoid code replication and simplify application. Filters can be very useful in many various scenarios. For example, you can use filters when you want to:
-ensure that user is logged in
-specify input and ouput of action methods
-apply policy to unhandled exception
-manipulate action arguments

There are five filter types. Each of them runs at the different stage of MVC action invocation pipeline:

  • Authorization filters – check if user is authorized for the request. If user in unauthorized, the request becomes short circuited.
     public class CustomAuthorizationFilter : IAuthorizationFilter
        {
            public void OnAuthorization(AuthorizationFilterContext context)
            {
               
            }
        }
    
  • Resource filters – used for logging, caching and model binding modification. They can be executed in the end of the pipeline as well.
  • public class CustomResourceFilter : IResourceFilter
        {
            public void OnResourceExecuted(ResourceExecutedContext context)
            {
                
            }
    
            public void OnResourceExecuting(ResourceExecutingContext context)
            {
               
            }
        }
    
  • Exception filters – their role is to handle exceptions that occur in filter pipeline. They can be very helpful in situation when you need to handle errors in different ways, depending on the invoked action.
     public class CustomExceptionFilter : IExceptionFilter
        {
            public void OnException(ExceptionContext context)
            {
               
            }
        }
    
  • Action filters – run before and after action method is invoked. They can be used to manipulate input arguments, controller instance and result of the action.
      public class CustomActionFilter : IActionFilter
        {
            public void OnActionExecuted(ActionExecutedContext context)
            {
            
            }
    
            public void OnActionExecuting(ActionExecutingContext context)
            {
               
            }
        }
    
  • Result filters – run (if action method execuded successfully) before and after action result execution. For example, they can be used to modify the HTTP response.
    public class CustomResultFilter : IResultFilter
        {
            public void OnResultExecuted(ResultExecutedContext context)
            {
                
            }
    
            public void OnResultExecuting(ResultExecutingContext context)
            {
                
            }
        }
    

Filters can be configured per action, per controller or globally.
Global filters can be added in Startup.cs class.

services.AddMvc(options =>  
   {  
       options.Filters.Add(typeof(CustomResultFilterAttribute));  //by type
       options.Filters.Add(new CustomActionFilterAttribute());   //by instance 
   });  

They can be added in two ways: by type and by instance. Adding filter by type causes that the same filter instance is used for all requests. If filter is added by type, it means that the new instance of this filter is created per each request.

Action and controller filters are applied by an attribute:

  [CustomActionFilter]
  public IActionResult Index()
  {
      return View();
  }

Leave a Reply

Your email address will not be published. Required fields are marked *