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).
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.
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句