简体   繁体   English

从 ASP.NET Web API 中的 URI 到字典的模型绑定

[英]Model binding to Dictionary from URI in ASP.NET Web API

Please refer to this link from MVC: http://aspnetwebstack.codeplex.com/discussions/351011请参考MVC的这个链接: http : //aspnetwebstack.codeplex.com/discussions/351011

I am having trouble with model binding.我在模型绑定方面遇到了问题。 From JavaScript I do an GET Ajax request to my API end point called "/api/products" passing in some parameters including paging and sorting as query parameters.我从 JavaScript 向名为“/api/products”的 API 端点发出 GET Ajax 请求,传入一些参数,包括分页和排序作为查询参数。 Here is the complete URI:这是完整的 URI:

http://localhost/api/products?page=1&count=10&filter[name]=Test1&filter[price]=10&sorting[name]=desc

On the server side, I have an Web API controller accepting these properties from the URI:在服务器端,我有一个 Web API 控制器从 URI 接受这些属性:

public async IHttpActionResult Get([FromUri]Dictionary<string,string> filter, [FromUri]Dictionary<string,string> sorting, int count, int page)
{
        //...
}

The "count" and "page" parameters bind perfectly fine, and the filter and sorting binds as an instance of a dictionary, but its count is 0. "count" 和 "page" 参数绑定得很好,过滤器和排序绑定为字典的实例,但其计数为 0。

I got this working in MVC but it doesn't seem to be doing the truck in Web API.我在 MVC 中得到了这个,但它似乎并没有在 Web API 中做卡车。

您仍然可以利用开箱即用的默认模型绑定器,您的 uri 看起来像

http://localhost/api/products?page=1&count=10&filter[0].key=name&filter[0].value=Test1&filter[1].key=price&filter[0].value=10&sorting[0].key=name&sorting[0].value=desc

I think it is better to use a model as parameter, such as:我认为最好使用模型作为参数,例如:

Public class model
{
Public Dictionary<string,string> filter{get;set;}
Public Dictionary<string,string> sorting{get;set;}
Public int sorting{get;set;}
}

public async IHttpActionResult Get(model yourModel)
{
        //...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM