如何使用GET方法发送JSON对象

我用WebApi2的控制器方法

[HttpGet] public IEnumerable GetProducts(ProductSearchCriteria searchCriteria) { //searchCriteria is always null here!!! Why? return db.Instance.LoadProducts(searchCriteria); } 

我的搜索条件类

 public class ProductSearchCriteria { private int id; private string name; private DateTime createdOn; [JsonProperty] public string Name { get { return this.name; } set { this.name = value; } } [JsonProperty] public DateTime CreatedOn { get { return this.createdOn; } set { this.createdOn = value; } } [JsonProperty] public int ID { get { return this.id; } set { this.id = value; } } } 

我在html页面中的脚本

  $("#btnTest").on("click", function () { var searchCriteria = {}; searchCriteria.ID = 0; searchCriteria.Name = ""; //searchCriteria.CreatedOn = ""; var url = "http://localhost:8080/api/products" $.getJSON(url, searchCriteria).done(processResponse); }); function processResponse(response){ }  

我达到了我的控制器方法(调试模式),但ProductSearchCriteria searchCriteria参数始终为null。 如何使用JQuery和WebApi2的get方法发送我的JSON对象?

您正在使用$.getJSON(url, searchCriteria)将查询发送到服务器$.getJSON(url, searchCriteria)并且getJSON 将searchCriteria作为url编码的查询字符串发送,因为您的searchCriteria将适合普通对象的定义

在服务器端,.NET Web API的默认参数绑定将在URL中查找“简单”数据类型(例如int,double,string),否则它将回退到正文内容。

要获取Web API模型绑定以从url中提取复杂类型,就像在ProductSearchCriteria类中一样,您需要在参数前面添加[FromUri]属性,如下所示:

 [HttpGet] public IEnumerable GetProducts([FromUri] ProductSearchCriteria searchCriteria) {} 

有关ASP.NET Web API中的参数绑定的详细信息,请参见此处

我认为值得尝试保留GET语义而不是切换到POST,正如一些人所建议的那样,因为你的代码实际上做了看起来像操作的东西,只要你不修改数据或状态…… GET似乎适用。

试试这个代码

 [HttpGet] public IEnumerable GetProducts([FromUri]ProductSearchCriteria searchCriteria) { //searchCriteria is always null here!!! Why? return db.Instance.LoadProducts(searchCriteria); } 

您可以尝试使用[FromUri]装饰参数。

 [HttpGet] public IEnumerable GetProducts([FromUri] ProductSearchCriteria searchCriteria) { //searchCriteria is always null here!!! Why? return db.Instance.LoadProducts(searchCriteria); } 

另一种选择是对您的JSON对象进行字符串化并在服务器端代码中对其进行缩减。 您可以使用JSON.NET等转换器执行此操作,也可以使用自定义类型转换器,模型绑定器或值提供程序。 更多信息可以在这里找到。

使用post而不是:

 $("#btnTest").on("click", function () { var searchCriteria = {}; searchCriteria.ID = 0; searchCriteria.Name = ""; //searchCriteria.CreatedOn = ""; var url = "http://localhost:8080/api/products" $.post(url, data, processResponse, 'json'); }); 

并将方法属性更改为:

 [HttpPost] public IEnumerable GetProducts(ProductSearchCriteria searchCriteria)