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

How to send a JSON object using GET method

我的控制器方法与 WebApi2

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

我的搜索条件class

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 对象?

试试这个代码

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

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

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

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

使用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)

您正在使用 $.getJSON(url, searchCriteria)getJSON sends the searchCriteria as a url-encoded query string because your searchCriteria would fit the definition of a plain object

将查询发送到服务器

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

要获取 Web API 模型绑定以从 url 中提取复杂类型,就像您的 ProductSearchCriteria class 您需要添加 [FromUri]参数前面的属性是这样的:

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

详情请看这里Parameter Binding in ASP.NET Web API

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