MVC web api GET参数始终为null

时间:2014-06-16 12:09:13

标签: ajax asp.net-mvc-4 post asp.net-web-api get

以下是我的ajax电话

                     $.ajax({
                     type: "GET",
                     url: "https://localhost/api/Client",
                     data:        JSON.stringify({"SortExpression":"clientName","SortDirection":"desc"}),
                     contentType: "application/json; charset=utf-8",
                     async: false,
                     cache: false,
                     dataType:'json',
                     error: function (data) {
                             alert("hi error buddy")
                     },
                     success: function (response) {
                         if (response) {
                           //todo
                         }
                     }
                 });

我的控制器

public List<Customer> Get([FromUri] SortFilter filter)
    {

    }

和我的模特

public class SortFilter
{
    public string SortExpression
    {
        get; set;
    }
    public string SortDirection
    {
        get;  set;
    }
}

但是我的控制器总是将参数作为NULL。我哪里错了?

2 个答案:

答案 0 :(得分:2)

您提供的是值,但不是密钥。因此,虽然模型绑定器可能能够识别SortFilter是什么,但它无法知道filter是什么。

尝试包装对象并为其指定密钥。也许是这样的:

JSON.stringify({"filter":{"SortExpression":"clientName","SortDirection":"desc"}})

答案 1 :(得分:0)

对查询字符串执行GET请求,该字符串不应该是JSON编码的。 POST和PUT数据可能是JSON编码,但不是GET。您的参数为null的原因是因为查询字符串是一个没有参数名称的单个字符串。

取代:

  

数据:JSON.stringify({&#34;的SortExpression&#34;:&#34; CLIENTNAME&#34;&#34; SortDirection&#34;:&#34;降序&#34;})

  

数据:{&#34;的SortExpression&#34;:&#34; CLIENTNAME&#34;&#34; SortDirection&#34;:&#34;降序&#34;}

您可以通过输入Web API方法的完整URL

直接检查WebAPI调用
  

https://localhost/api/Client?SortExpression=clientName&SortDirection=desc

这将允许您调试数据检索器,并单独分页,这将使整个过程更容易。