Middleware vs Filter

Middleware in .NET Core

  1. It operates at a lower level and is part of the request pipeline.
  2. Executed for every request and can participate in the request-handling process from start to finish.
  3. Applied globally to the entire application or conditionally to specific routes.
  4. Configured in the Startup.cs file and used for broader concerns like authentication, logging, and routing.
  5. Examples include UseAuthentication, UseLogging, and UseMvc.
  6. Used for handling cross-cutting concerns at a lower level, not limited to MVC.
  7. Has direct access to the HTTP Context and can operate on the request and response at a lower level.
  8. The execution order is determined by the order in which the middleware components are added to the pipeline in the Startup.cs file.

Filters in .NET Core

  1. Filter has access to a wider MVC Context which helps us to access routing data and model binding information.
  2. Applied during the execution of MVC actions.
  3. Applied to controller actions in MVC.
  4. Used for MVC-specific concerns such as logging, authorization, and validation.
  5. Examples include AuthorizeAttribute, ActionFilterAttribute, and ResultFilterAttribute.
  6. Used for adding cross-cutting concerns related to MVC actions.
  7. Has access to the HttpContext but primarily focuses on MVC-related processing.
  8. The order of execution is determined by the order in which the filters are applied.
  9. Filters can be applied globally or on individual controllers/actions.

Choose Middleware when you only need HttpContext access. Opt for Filters when dealing with MVC-specific details like routing or model binding. It's about selecting the right tool for the specific task at hand.