2

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.

3 Answers 3

2

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.

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

5 Comments

I tried this, but my model parameter is always null. I have an "orderNumber" in query string and an OrderNumber property in my model class, but it doesn't seem to bind. Not sure if I'm missing something obvious.
Binds fine when I use a standard MVC controller.
Seems you need to use the [FromUri] attribute - e.g. public HttpResponseMessage Post([FromUri] MyModel model).
This doesn't work if you want to accept both POST and GET operations. You can use [FromUri] but then it'll only work from the querystring not from PostBuffer or for raw data. This is a major downer for Web API actually - the flexibility is much less than what MVC provides in ModelBinding.
2

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.

Comments

1

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);
    }
}

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.