dommer
dommer

Reputation: 19820

Can I map multiple query string values to a single controller (object) parameter?

I'm building an ASP.NET Web API REST service.

The calls (URLs) I have to process are fixed by another party and have numerous query string parameters.

Rather than have my controller take a dozen parameters, is there any way that I can map the query parameters to an object and pass that through to the controller?

I know that I could access them within the controller through GetQueryNameValuePairs, but I was wondering if there was a way to use data binding in this fashion.

Upvotes: 2

Views: 5932

Answers (3)

dommer
dommer

Reputation: 19820

ASP.NET Web API seems to require the use of the [FromUri] when passing a model object to a controller. For example:

public HttpResponseMessage Post([FromUri] MyModel model) { ... }

See this MSDN blog post for more details.

Upvotes: 2

Sando
Sando

Reputation: 667

I would simply create a query string parser:

protected IDictionary<string, string> GetQueryParameters(string queryString)
{
    var retval = new Dictionary<string, string>();
    foreach (var item in queryString.TrimStart('?').Split(new[] {'&'}, StringSplitOptions.RemoveEmptyEntries))
    {
        var split = item.Split('=');
        retval.Add(split[0], split[1]);
    }
    return retval;
}

And then from controller call:

public class DummyController : ApiController
{
    [HttpGet]
    public string SayHello(string name="")
    {
        var q = GetQueryParameters(Request.RequestUri.Query);

        return string.Format("Hello {0}", name);
    }
}

Upvotes: 1

Matthew Abbott
Matthew Abbott

Reputation: 61599

Yes,

Define a model, e.g.:

public class InputModel
{
    public string Param1 { get; set; }
    public string Param2 { get; set; }
}

Then adjust your action:

public HttpResponseMessage Put(InputModel model) { ... }

Much like MVC, the API controllers support Model Binding, there is an infrastructure in place to handle this, which itself is extensible. I'd google for examples of ASP.NET MVC Model Binding.

Upvotes: 2

Related Questions