1

My MVC 4 web service has a new use case. I need to pass a list of arguments on the query string to a Web API, e.g.,

http://host/SomeWebApi?arg=x&arg=y

I previously did this simply and easily in my Web Site controller using ICollection<string> arg as a parameter in the controller. That is working now, but it is a Web page, as opposed to an API.

Now I am knocking my head against the wall trying to get a Web API version of the same thing to work. I've made a simple test interface, below, and the collection arg is always null. I've tried List<string> and string[] as types as well. What am I overlooking?

Route register:

config.Routes.MapHttpRoute(
    name: "Experiment",
    routeTemplate: "Args",
    defaults: new
    {
        controller = "Storage",
        action = "GetArgTest",
        suite = UrlParameter.Optional,
    },
    constraints: new
    {
        httpMethod = new HttpMethodConstraint(new HttpMethod[] { new HttpMethod("GET") })
    }
);

Web API controller code:

public string GetArgTest(ICollection<string> suite)
{
    if (suite == null)
    {
        return "suite is NULL";
    }
    else
    {
        return "suite is NON-NULL";
    }
}

Test query string that results in "suite is NULL":

http://localhost:5101/Args?suite=1&suite=2
2
  • If I use GetArgTest(string suite), then I get a non-NULL value, but the text says "(Collection)". Super frustrating. Commented May 23, 2013 at 15:29
  • Sadly, I timed out on this issue, and resorted to: List<string> suite = new List<string>(); IEnumerable<KeyValuePair<string, string>> queryPairs = Request.GetQueryNameValuePairs(); foreach (var pair in queryPairs) { if (pair.Key == "suite") { suite.Add(pair.Value); } } Commented May 23, 2013 at 18:08

1 Answer 1

2

I came across this answer ApiController Action Failing to parse array from querystring and discovered that to resolve this you need to put in the FromUriAttribute. So in your example:

public string GetArgTest([FromUri]ICollection<string> suite)
{
}

This makes sense I guess, typically with an API controller you'd expect to be doing more POST and PUT requests for which you'd typically include post data rather than a QueryString.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.