加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net web-api – ASP.Net Web API模型绑定不工作像在MVC 3

发布时间:2020-12-15 18:54:01 所属栏目:asp.Net 来源:网络整理
导读:我的印象是,ASP.Net Web API中的模型绑定应该支持与MVC支持的相同的最低级别的功能的绑定。 拿下面的控制器: public class WordsController : ApiController{ private string[] _words = new [] { "apple","ball","cat","dog" }; public IEnumerablestring
我的印象是,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; }
}

我要求:

http://localhost:62855/api/words?search=a&max=2

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

解决方法

看看这个: How WebAPI does Parameter Binding

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

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

要么

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读