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

Solutions Architect at Edgeside Solutions
.NET and C# aficionado with an interest in architecture, patterns, practices, and more. Microsoft fanatic.

Latest posts by Sean Leitzinger (see all)

Leave a Reply

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