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

C# ASP.NET Web API中从URI到字典的模型绑定,c#,javascript,asp.net,asp.net-web-api,C#,Javascript,Asp.net,Asp.net Web Api,请参阅MVC的此链接: 我在模型绑定方面遇到了问题。从JavaScript中,我向名为“/API/products”的API端点发出GET-Ajax请求,并将一些参数(包括分页和排序)作为查询参数传入。以下是完整的URI: http://localhost/api/products?page=1&count=10&filter[name]=Test1&filter[price]=10&sorting[name]=desc 在服务器端,我有一个Web API控制器

请参阅MVC的此链接:

我在模型绑定方面遇到了问题。从JavaScript中,我向名为“/API/products”的API端点发出GET-Ajax请求,并将一些参数(包括分页和排序)作为查询参数传入。以下是完整的URI:

http://localhost/api/products?page=1&count=10&filter[name]=Test1&filter[price]=10&sorting[name]=desc
在服务器端,我有一个Web API控制器,从URI接受以下属性:

public async IHttpActionResult Get([FromUri]Dictionary<string,string> filter, [FromUri]Dictionary<string,string> sorting, int count, int page)
{
        //...
}
public async IHttpActionResult Get([FromUri]字典过滤器,[FromUri]字典排序,整数计数,整数页)
{
//...
}
“count”和“page”参数绑定得非常好,过滤器和排序绑定为字典实例,但其计数为0


我在MVC中实现了这一点,但它似乎没有在Web API中实现卡车功能。

我认为最好使用模型作为参数,例如:

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)
{
        //...
}
公共类模型
{
公共字典筛选器{get;set;}
公共字典排序{get;set;}
公共整数排序{get;set;}
}
公共异步IHttpActionResult获取(模型yourModel)
{
//...
}

您仍然可以利用现成的默认模型绑定器,您的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

嗨,Shahrooz,我试过了,但它仍然不能正确地绑定到字典上properties@FanieReynders请阅读:据我所知,WebAPI中的modelbinding与mvc@FanieReynders是的,非常不同检查@LawrenceAiello提出的解决方案,很明显,上述链接不是指向非现场资源的链接,而是URL格式的一个示例。