Building restful API using asp.net core 3. X – 4.2 filtering and searching

Time:2020-2-11

Passing parameters to the web API

Data can be passed to the API in many ways. 

Binding Source Attributes Would tell Model Where does the binding engine find the binding source for. 

There are six types Binding Source Attributes: 

  • [FromBody] 

    • Requested body 

  • [FromForm] 

    • Form data in the requested body 

  • [FromHeader] 

    • Requested header 

  • [FromQuery] 

    • Query string parameter 

  • [FromRoute] 

    • Routing data in current request 

  • [FromService] 

    • Services injected as action parameters 

 

For example: 

public async Task<ActionResult<CompanyDt0>> 
O references 
GetCompany( [FromRoute]Guid companyld)

Or: 

public async Task<ActionResult<CompanyDt0>> 
O references 
GetCompany([FromQuery]Guid companyld)

 

By defaultASP.NET Core Will use Complex Object Model Binder, it will transfer data fromValue ProvidersIt’s extracted there, andValue ProvidersThe order of is defined. 

But we buildAPIUsually used [ApiController] This attribute, for better adaptationAPIIt changes the rules above. The changed rules are as follows: 

  • [FromBody] 

    • It is usually used to infer complex type parameters. 

  • [FromForm] 

    • Usually used to inferIFormFileandIFormFileCollectionTypeActionParameters. 

  • [FromRoute] 

    • InferActionThe parameter name of is consistent with the parameter name in the routing template. 

  • [FromQuery] 

    • Used to infer otherActionParameters. 

     

According to these rules, theActionBy using these properties in front of the parameters of, we can avoid looking for the binding source manually. You can also use these when the default behavior rules need to be overridden Binding Source Attributes 

 

filter

Filtering a set means to limit the returned set according to the conditions. 

For example, I want to return to all European companies that are state-owned. beURIFor:GET /api/companies?type=State-owned&region=Europe 

So filtering means: we pass the name of a field and the value that we want to match toAPI, as part of the returned collection. 

 

search 

Searching for a set refers to adding qualified data to the set according to predefined rules. 

The search is actually out of the filter. For search, the field name to be matched is not usually passed, and the value to be searched is usually passed toAPIAnd thenAPIDecide which fields to look up the value for. It’s often full-text search. 

For example:GET /api/companies?q=xxx 

 

filter vs search 

You can see that filtering and searching are different. 

Filtering: first, a complete set, then matching according to the conditions/Unmatched data items removed. 

Search: first an empty set, then match the/Mismatched data items are added to it. 

 

But it should be noted that: 

Filtering and searching for these parameters is not part of the resource. 

Filtering is only allowed for fields of resources.