asp.net web api - model binding list parameter

最后都变了- 提交于 2019-12-07 09:25:01

问题


In my controller I have:

[AcceptVerbs("GET", "POST")]
    public List<BuzzMonitor.Web.Message> Search(string text, DateTime dateFrom, DateTime dateTo, List<int> themeIds, List<int> sourceIds) 
    {...}

and I want to do model binding. It's easy for primitive types, but what to do when I have a list of primitive types?

I did it like this in Global.asax:

 GlobalConfiguration.Configuration.Routes.MapHttpRoute("SearchWithParameters", "api/{controller}/{action}/{text}/{dateFrom}/{dateTo}/?/?"

But I dont know what to set for lists...

I found on some site that I can add [ModelBinder] before list, but when I do that I just get red underline on that word.

Does anyone have an idea how to do it?


回答1:


From your description it looks like you have found this article or one like it

http://lostechies.com/keithdahlby/2012/10/04/asp-net-web-api-list-parameter-binding/

recommending you use the ModelBinder attribute. I still recommend this way if you can get it to work. The red underline you describe sounds like you may not have the appropriate references. Please make sure you have the appropriate references in your class to access that attribute, in this case it looks like System.Web.Http.ModelBinding

http://msdn.microsoft.com/en-us/library/system.web.http.modelbinding.modelbinderattribute(v=vs.118).aspx

If that fails you will likely not be able to use Model Binding. From the first article

Web API only uses model binding for “simple types”

you can also look at using a JSON Formatter or similar, this is not difficult and would easily support List structures, with well formatted JSON.

here is a great introductory article to using this

http://www.hanselman.com/blog/OneASPNETMakingJSONWebAPIsWithASPNETMVC4BetaAndASPNETWebAPI.aspx



来源:https://stackoverflow.com/questions/23933580/asp-net-web-api-model-binding-list-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!