ASP.NET Core 2.2 & 3 REST API #28 — Resource Filtering

Theodoros Ntakouris
2 min readSep 24, 2019

--

We’re already doing some resource filtering with the pagination logic, let’s take this a step further, filtering our Posts object, by query parameters.

In this use case, we want to filter posts by owner id (user id). Just pass a new query parameter on our controller method, and then change the PostService to include it.

In our service, we can refactor it a bit to make it easy to use for our filtering, extracting a queryable ( DbSet<> ) in order to be able to optionally apply a predicate before hitting the database, with the filter actually being as simple as x => x.UserId == userId

This is fine and all, working as expected, but what happens when you want to add a second and a third and a fourth… filter? We are not going to add more and more query parameters, the namespace is going to be polluted with such big method signature. We are going to extract a new filter object, the same way we did with our pagination.

Under Contracts/V1/Requests/Query create a GetAllPostsQuery class.

The next logical step would be to also change the signature of our controller method, and the service method as well.

Go ahead and create the GetAllPostsFilter , in our domain objects, and then just register this with the auto mapper, ending up with the following map and endpoint code:

Everything is set up properly, with the last thing to change being userId => filter?.UserId .

Realistically, we should extract the if statement in it’ s own method, because it would get chaotic with multiple filters, and nobody could tell what our method is doing by just taking a glance. Extract that method and call it AddFiltersOnQuery

Pro tip: Move private and/or helper methods on the bottom of each file

Code is available on Github and the instructional videos are located on YouTube.

Keep Coding

--

--

Responses (1)