ASP.NET Core middleware vs filters

There is a video about this on channel 9: ASP.NET Monsters #91: Middleware vs. Filters. To summarize the video:

The execution of request starts and we have a middleware, and another middleware, think of it like the "Russian dolls inside of dolls" and eventually the routing middleware kicks in and then request goes into the MVC pipline. enter image description here So if you don't require the context of MVC (let's say you're concerned about flow and execution, like responding to headers some pre-routing mechanism, etc.) then use middlewares.
But if you require the context of MVC and you want to operate against actions then use filters.


Middleware operate on the level of ASP.NET Core and can act on every single request that comes in to the application.

MVC filters on the other hand only run for requests that come to MVC.

So for example, if I wanted to enforce that all requests must be done over HTTPS, I would have to use a middleware for that. If I made an MVC filter that did that, users could still request e.g. static files over HTTP.

But then on the other hand something that logs request durations in MVC controllers could absolutely be an action filter.


The execution of middleware occurs before the MVC context becomes available in the pipeline. That is, middleware does not have access to the ActionExecutingContext or the ActionExecutedContext 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.

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.

Source and example: dotnetcultist.com