I was under the impression that model binding in the ASP.Net Web API was supposed to support binding with the same minimum level of functionality supported by MVC.
Take the following controller:
public class WordsController : ApiController
{
private string[] _words = new [] { "apple", "ball", "cat", "dog" };
public IEnumerable<string> Get(SearchModel searchSearchModel)
{
return _words
.Where(w => w.Contains(searchSearchModel.Search))
.Take(searchSearchModel.Max);
}
}
public class SearchModel
{
public string Search { get; set; }
public int Max { get; set; }
}
I'm requesting it with:
http://localhost:62855/api/words?search=a&max=2
Unfortunately the model does not bind as it would in MVC. Why is this not binding as I would expect? I'm going to have a lot of different model types in my application. It would be nice if binding just worked, like it does in MVC.
I have found the entire Web API 2 to be a difficult learning curve with lots of "Gotchas" I have read a few of the key books that cover many arcane nuances of this rich product offering. But basically, I thought there must be some core functionality that could take advantage of the best of the features. So, I set out to do four straight forward tasks. 1. Accept a query string, from a browser, into an Api2 Client and populate a simple .NET model. 2. Have the Client submit an async Post to an Api2 Server encoded in JSON extracted from the prior Model 3. Have the Server do a trivial conversion on the Post Request from the Client. 4. Pass it all back up to the Browser. This is it.
Take a look at this: How WebAPI does Parameter Binding
You need to decorate your complex parameter like so:
OR