ASP.Net Web API模型绑定不像MVC 3那样工作

Nat*_*ley 25 model-binding custom-model-binder asp.net-web-api jquery-datatables-editor

我的印象是,ASP.Net Web API中的模型绑定应该支持具有MVC支持的相同最低功能级别的绑定.

拿以下控制器:

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; }
}
Run Code Online (Sandbox Code Playgroud)

我要求它:

http://localhost:62855/api/words?search=a&max=2
Run Code Online (Sandbox Code Playgroud)

不幸的是,模型没有像在MVC中那样绑定.为什么这不像我期望的那样具有约束力?我的应用程序中会有很多不同的模型类型.如果绑定工作就好了,就像在MVC中一样.

Mic*_*ird 26

看看这个:WebAPI如何进行参数绑定

你需要装饰你的复杂参数,如下所示:

public IEnumerable<string> Get([FromUri] SearchModel searchSearchModel)
Run Code Online (Sandbox Code Playgroud)

要么

public IEnumerable<string> Get([ModelBinder] SearchModel searchSearchModel)
Run Code Online (Sandbox Code Playgroud)