ASP.Net Web API model binding not working like it does in MVC 3

Nathan Ridley picture Nathan Ridley · Jun 2, 2012 · Viewed 10.7k times · Source

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.

Answer

Michael Baird picture Michael Baird · Jun 2, 2012

Take a look at this: How WebAPI does Parameter Binding

You need to decorate your complex parameter like so:

public IEnumerable<string> Get([FromUri] SearchModel searchSearchModel)

OR

public IEnumerable<string> Get([ModelBinder] SearchModel searchSearchModel)