Web API 2: how searching

11,005

Solution 1

  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.

Solution 2

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.

Share:
11,005

Related videos on Youtube

Tom
Author by

Tom

Updated on September 14, 2022

Comments

  • Tom
    Tom about 1 year

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

  • aruno
    aruno almost 6 years
    Just my experience trying to use ODATA was one of the worse decisions I made and the most annoying weekends. When I look back at the code I have no clue how it works.