Global Filters VS Middleware

Viewed 24

I have wrote some API in my project for getting some data. Now I have a condition for filtering result data. I don't want to repeat the same filtering in each controller, so I decided filtering result after executing. I have to option: using result filter (after fetching data) or using middleware where I will filter data in each request. Could you explain me when I should use result filter and when middleware. Is there any difference in these approaches?

1 Answers

This is the request pipeline for ASP.NET Core Web API

enter image description here

The result filter will be executed at the last of the execution pipeline, so if you do not want to execute the entire pipeline just for filter better use middleware.

Middleware does not have access to ASP.NET MVC context, Model binding, IActionResult, ModelState so if you need any of these you will have to use filters otherwise middleware.

Related