DenaliHardtail
DenaliHardtail

Reputation: 28336

How do I handle multiple parameters as an OR in a Web API querystring?

Suppose I have this URL:

api.XXX.com/cities?risk=a,b&rating=x,y

What I want is a list of cities with a Risk category of A or B AND a Rating of X or Y. How should I implement this?

I understand I can get the values of the Risk and Rating keys but then what? Is it best to simply parse the string and use a switch statement? Or is there a better approach?

Upvotes: 2

Views: 1449

Answers (2)

StriplingWarrior
StriplingWarrior

Reputation: 156634

A more standard approach would be:

api.XXX.com/cities?risks=a&risks=b&ratings=x&ratings=y

Which could be handled by a controller action something like this:

[HttpGet]
public async Task<IHttpActionResult> SearchCities(
    List<string> risks,
    List<string> ratings)
{
    var results = this.dbContext.Cities.AsQueryable();
    if(risks.Any()) 
    {
        results = results.Where(c => c.Risks.Any(cr => risks.Contains(cr.Code));
    }
    if(ratings.Any())
    {
        results = results.Where(c => ratings.Contains(c.Rating));
    }
    ...
}

Similar answer here.

Upvotes: 5

Jesse Carter
Jesse Carter

Reputation: 21187

I'd recommend creating a POCO to represent the options that this endpoint will be receiving:

public class CitySearchOptions
{
   public List<string> Risk { get; set; }
   public List<string> Rating { get; set; }
}

You can then use the [FromUri] attribute in your controller signature to have the query string be automatically deserialized into your POCO. From there you can easily implement logic to act on the received values.

public async Task<IHttpActionResult> SearchCities([FromUri] CitySearchOptions options)

Note that the above is psuedo code and might not work for you out of the box without a few tweaks to the format of your query string. This question suggests that for list based query params you should prefer a format like this:

/cities?risk=a&risk=b&rating=x&rating=y

Upvotes: 0

Related Questions