In ASP Web API 2 i'd like to implement a search feature in my REST URI.
For example if i have the resource Customers
/base_url/customers
/base_url/customers/1
....
i'd like for example implement:
/base_url/customers?active=true
How can i implement the searching in the Web API 2 controller? (I don't want use the OData protocol because i have DTO object: my controller must interface with DTO object and not directly with model objects).
In its simplest form, a Web API is an API over the web (HTTP). ASP.NET Web API is a framework that allows you to build Web API's, i.e. HTTP-based services on top of the . NET Framework using a convention based and similar programming model, as that of ASP.NET MVC.
Define a search options class with all the properties that you want your client to search on. Lets call it CustomerSearchOptions for now:
public class CustomerSearchOptions
{
public bool IsActive { get; set; }
public string AnotherProperty {get; set;}
}
Define a Get method on your api controller that gets a parameter of type CustomerSearchOptions, and make the parameter decorated by [FromUri] attribute.
The implementation of the get method will search your repository using the search options and return the matching data (MyCustomerDto):
[HttpGet]
[ResponseType(typeof(List<MyCustomerDto>))]
public async Task<IHttpActionResult> SearchAsync([FromUri] CustomerSearchOptions searchOptions)
{
if (searchOptions == null)
{
return BadRequest("Invalid search options");
}
var searchResult = await myRepo.SearchAsync(searchOptions);
return Ok(searchResult);
}
/base_url/customers?isActive=true&anotherProperty=somevalue
That's all.
Hope that helps.
You should follow the practice of putting the query in the url with the as described above when possible, but you also have to remember that an api is designed to make a developers life easier. If your search conditions are complex this may not work.
We had for a customer service team where they wanted to have a washed down version of the entities exposed with ranges and conditions for each property and they wanted to be able to access some related properties as well. While we could have made this work in a URL it would have drove our front end team nuts! So we adopted the conventions that POSTs to .../api/entity/queries would be used for these complex searches.
At first I was apposed to using a POST like this, but it really made the whole process a lot simpler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With