1

我使用 WebApi2 的控制器方法

    [HttpGet]
    public IEnumerable<Products> 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页面中的脚本

<script>
    $("#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){
    }
</script>

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

4

4 回答 4

0

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

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

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

于 2017-03-23T21:37:43.077 回答
0

使用 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<Products> GetProducts(ProductSearchCriteria searchCriteria)
于 2017-03-23T21:42:23.077 回答
0

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

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

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

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

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

我认为值得尝试保留 GET 语义而不是像某些人建议的那样切换到 POST,因为您的代码实际上正在执行看起来像读取操作的操作,并且只要您不修改数据或状态... GET 似乎适用。

于 2017-03-23T22:11:44.670 回答
-1

试试这个代码

[HttpGet]
public IEnumerable<Products> GetProducts([FromUri]ProductSearchCriteria searchCriteria)
{
    //searchCriteria is always null here!!! Why?
    return db.Instance.LoadProducts(searchCriteria);
}
于 2017-03-23T21:34:36.267 回答