Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web API - How to pass in arbitrary number of parameters like args in console applications?

Using ASP.NET Web API, is there a way for me to pass in an arbitrary number of parameters using the URI in the same fashion as they are input to a console application using the args keyword. In the Web API case, the parameters would be separated by forward slashes (/). So let's say I have a method in a controller MessageController such as this:

public string Get(params string[] args)
{
    string returnValue = "";

    for (int i=0;i < args.Length; i++)
    {
        returnValue += args[i] + " ";
    }

    return returnValue;
}

I would like to go to:

../api/Message/a/b/c/d/e/f/g/h/i

and it should return the string:

a b c d e f g h i

The tricky part is getting the parameters to bind to the type string[] instead of providing an object with multiple string properties. Does anyone know of a way to accomplish this? Thank you.

EDIT: The params keyword was left in there but I'm not sure if Web API routing knows how to handle params.

like image 273
Anshul Avatar asked Sep 02 '25 03:09

Anshul


1 Answers

Here is a great blog post by Tugberk that shows how to do it:

http://www.tugberkugurlu.com/archive/asp-net-web-api-catch-all-route-parameter-binding

In short you use a combination of a catch all route + HttpParameterBinding.

like image 161
Yishai Galatzer Avatar answered Sep 04 '25 21:09

Yishai Galatzer