How should I pass multiple parameters to an ASP.Net Web API GET?

sig606 picture sig606 · Jun 7, 2012 · Viewed 316.9k times · Source

I am using the .Net MVC4 Web API to (hopefully) implement a RESTful api. I need to pass in a few parameters to the system and have it perform some action, then return a list of objects as the results. Specifically I am passing in two dates and returning records that fall between them. I'm also keeping track of the records returned so that subsequent calls do not get reprocessed in the system.

I've considered a few approaches:

  1. Serializing the params into one single JSON string and picking it apart in the API. http://forums.asp.net/t/1807316.aspx/1

  2. Pass the params in the query string.
    What is best way to pass multiple query parameters to a restful api?

  3. Defining the params in the route: api/controller/date1/date2

  4. Using a POST that inherently lets me pass an object with params.

  5. Researching ODATA since the Web API (currently) supports it. I haven't done much with this yet so I'm not very familiar with it.

It seems that proper REST practices indicate when data is pulled, you should use a GET. However, GET should also be nullipotent (produces no side-effects), and I wonder if my specific implementation violates that since I mark records in the API system, hence I am producing side-effects.

It also led me to the question of supporting variable parameters. If the input parameter list changes, it would be tedious to have to re-define your route for Choice 3 if that happens a lot. And what might happen if the parameters are defined at run-time...

In any case, for my specific implementation, which choice (if any) seems best?

Answer

Mark Pieszak - Trilon.io picture Mark Pieszak - Trilon.io · Nov 4, 2014

I think the easiest way is to simply use AttributeRouting.

It's obvious within your controller, why would you want this in your Global WebApiConfig file?

Example:

    [Route("api/YOURCONTROLLER/{paramOne}/{paramTwo}")]
    public string Get(int paramOne, int paramTwo)
    {
        return "The [Route] with multiple params worked";
    }

The {} names need to match your parameters.

Simple as that, now you have a separate GET that handles multiple params in this instance.