Middleware vs Filters ASP. NET Core

If you’ve been working in ASP.NET Core then you’ve probably been faced with the dilemma of choosing between using middleware or filters. Both middleware and filters can serve similar purposes. Choosing between them comes down to whether you need access to the MVC context.

ASP.NET Core Middleware

The execution of middleware occurs before the MVC context becomes available in the pipeline. That is, middleware does not have access to the ActionExecutedContext or the ActionExecutingContext in the case of an ActionFilter for example. What you do have access to is the HttpContext, which will allow you to perform actions on the request as well as the response. Since model binding hasn’t occurred yet, using middleware would not be suited to running a validation function or modifying values. Middleware will also run on every request regardless of which controller or action is called.

ASP.NET Core Filters

On the other hand, filters will only run on specified actions and controllers unless you register the filter globally in the startup. Since you have full access to the context you can also access the controller and action itself. Running with the example above using validation, you can run through the full modelstate on the ActionExecutingContext. See below:

public class ValidationFilter : ActionFilterAttribute
    public override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        var modelState = context.ModelState;

        if (!modelState.IsValid)
            var errors = modelState.Values.SelectMany(v => v.Errors).Select(m => m.ErrorMessage).ToList();
            var stringBuilder = new StringBuilder();
            errors.ForEach(m => stringBuilder.AppendLine(m));
            context.Result = new BadRequestObjectResult(stringBuilder.ToString());

            return base.OnActionExecutionAsync(context, next);

        return base.OnActionExecutionAsync(context, next);


Sean Leitzinger

Comments (3)

  1. AK Hasanuzzaman
    February 17, 2020

    Good one thanks.

  2. Billy Larru
    February 19, 2020

    Excelente explicación, se agradece el aporte.

Leave a comment

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