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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.