Filters

Built-in Filter Types

ASP.NET MVC supports the following four types of filters:

  1. Authorization Filters: Used to implement authentication and authorization logic.

    • Example: [Authorize]

  2. Action Filters: Used to run code before and after an action method is called.

    • Example: [HandleError]

  3. Result Filters: Used to run code before and after the action result is executed.

    • Example: Custom logging before a view is rendered.

  4. Exception Filters: Used to handle exceptions thrown by action methods or action results.

    • Example: [HandleError] with specific exception types.

Adding Custom Filters

While the built-in filters cover many common scenarios, you can create custom filters to handle additional logic. To create a custom filter, you typically inherit from one of the filter base classes or implement an appropriate filter interface.

Example: Custom Action Filter

Let's create a custom action filter that logs the execution time of an action method.

  1. Create the Custom Filter:

    using System.Diagnostics;
    using System.Web.Mvc;
    
    public class ExecutionTimeLoggerAttribute : ActionFilterAttribute
    {
        private Stopwatch stopwatch;
    
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            stopwatch = Stopwatch.StartNew();
        }
    
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            stopwatch.Stop();
            var executionTime = stopwatch.ElapsedMilliseconds;
            filterContext.HttpContext.Response.Headers.Add("X-ExecutionTime-ms", executionTime.ToString());
        }
    }
  2. Apply the Custom Filter:

    You can apply the custom filter at the action, controller, or global level.

    • Action Level:

      public class HomeController : Controller
      {
          [ExecutionTimeLogger]
          public ActionResult Index()
          {
              return View();
          }
      }
    • Controller Level:

      [ExecutionTimeLogger]
      public class HomeController : Controller
      {
          public ActionResult Index()
          {
              return View();
          }
      }
    • Global Level:

      To apply the filter globally to all controllers and actions, register it in FilterConfig.cs:

      public class FilterConfig
      {
          public static void RegisterGlobalFilters(GlobalFilterCollection filters)
          {
              filters.Add(new ExecutionTimeLoggerAttribute());
              // Other filters
          }
      }

      Make sure to call the RegisterGlobalFilters method in your Global.asax file:

      protected void Application_Start()
      {
          AreaRegistration.RegisterAllAreas();
          FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
          RouteConfig.RegisterRoutes(RouteTable.Routes);
          BundleConfig.RegisterBundles(BundleTable.Bundles);
      }

Summary

ASP.NET MVC supports four built-in filter types: Authorization Filters, Action Filters, Result Filters, and Exception Filters. Developers can extend the filtering capability by creating custom filters tailored to specific needs. These custom filters can be applied at the action, controller, or global level, allowing for flexible and reusable logic throughout the application.

Last updated