Web API 2: how searching

Tom

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).

Omar.Alani
  1. 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;}
    }
    
  2. Define a Get method on your api controller that gets a parameter of type CustomerSearchOptions, and make the parameter decorated by [FromUri] attribute.

  3. 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);
        }
    
    1. The client of your web api needs to call your api passing the search options in the query string NOT in the message body.

    /base_url/customers?isActive=true&anotherProperty=somevalue

That's all.

Hope that helps.

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章