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); } }
AK Hasanuzzaman
February 17, 2020Good one thanks.
Billy Larru
February 19, 2020Excelente explicación, se agradece el aporte.
Jaco
April 11, 2020From .NET Core 3 you can use features to pass data from MVC to middleware and vice/versa. So you could for example make the ModelState available for use in middleware as well. Have a look at https://stackoverflow.com/questions/52370655/access-modelstate-in-asp-net-core-middleware/52379243 for an example.