C#WebApi查询参数解析

时间:2017-05-14 06:05:09

标签: c# asp.net-web-api query-string querystringparameter

我有一个来自jquery网格的查询字符串,我试图将其解析为C#Web API中的参数,但是我无法获取其中一个属性来填充。

查询字符串:

?current=1&rowCount=10&sort[received]=desc&sort[email]=asc&sort[id]=desc&searchPhrase=

方法:

public IEnumerable<IUserDto> Get(int current, int rowCount, NameValueCollection sort, string searchPhrase)

&#39;排序&#39;参数始终为null,其他所有参数都正确填充。我已经为参数尝试了多种类型,但无论我尝试过什么,我总是以null参数结束。

对参数类型的任何指示或建议都表示赞赏。

1 个答案:

答案 0 :(得分:0)

如果要从查询字符串反序列化复杂聚合值(例如NameValueCollection),则需要使用FromUriAttribute修饰参数。这并不保证它可以通过任何方式工作,但除非您定义了自定义参数处理程序,否则它将无法工作。

public IEnumerable<IUserDto> Get(
    int current,
    int rowCount,
    [FromUri] NameValueCollection sort,
    string searchPhrase
) { ... }

此外,您需要确保序列化到URL中的内容实际上是JSON格式的字典。从您发布的网址中,您似乎是将本地对象中的receivedidemail属性添加为单独的查询字符串参数

&sort[received]=desc&sort[email]=asc&sort[id]=desc

WebAPI的参数绑定不会自动将它们聚合成字典。

您可以像

一样构建它
var sortParam = ['received', 'id', 'email'].reduce(function (o, key) {
  o[key] = sort[key];
  return o;
}, {});

var queryParams = '?current=' + 1 + 
                  '&rowCount' = 10 + 
                  '&sort=' + JSON.stringify(sortParam) +
                  '&searchPhrase=' + something;

我还建议更改顺序,以便sort参数最后。