asp.net core middleware vs filters

后端 未结 3 1726
星月不相逢
星月不相逢 2020-12-02 12:57

After reading about asp.net core middlware, I am confused when should I use filters and when should I use middlewares as they seem to achieve the same goal. When should midd

3条回答
  •  旧时难觅i
    2020-12-02 13:28

    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

提交回复
热议问题