0

Suppose I have a resource in ASP.NET like so:

/api/cars

and I want to expose information about cars for sale. I want to expose it in two ways:

/api/cars?model=camry

/api/cars?make=toyota

I can implement the search for one of them, but not both at the same time since their signatures are identical. I'm using an ApiController in .NET 4.5: how can I implement both searches on the same resource?

Scott Jordan
  • 122
  • 1
  • 6

2 Answers2

1

You can use nullable input parameters. Since you are using strings, you don't even have to declare them as nullable. See this SO article. The gist is

public ActionResult Action(string model, string make)
{
    if(!string.IsNullOrEmpty(model))
    {
        // do something with model
    }

    if(!string.IsNullOrEmpty(make))
    {
        // do something with make
    }
}

As described in the linked SO article, any of the following routes will direct you to the right action:

  • GET /api/cars
  • GET /api/cars?make=toyota
  • GET /api/cars?model=camry
  • GET /api/cars?make=toyota&model=camry

Here is another good SO article on the subject.

Community
  • 1
  • 1
Coda17
  • 584
  • 6
  • 19
0

I'm assuming that you are using WebApi (e.g. your ApiController is System.Web.Http.ApiController)

Then your controller method will simply be

public HttpResponseMessage GetCars([FromUri] string make, [FromUri] string model) {
    ... code ...
}
gaiazov
  • 1,908
  • 14
  • 26