jquery - 通过 GET 将 JSON 数组传递给 MVC Web API

我知道这个主题有很多答案,但找不到我的问题的解决方案。 我有一个如下所示的 ASP.NET MVC Web API:

    [HttpGet]
    public IList<Country> GetCountryList(List<long> idList)

我试过这样调用它:

    $.ajax({
        dataType: "json",
        data: JSON.stringify({idList: listOfIds}),            
        type: "GET",
        url: "api/v1/util/CountryList",
        success: function (result) {
            alert(result);
        }
    });

然后 URL 如下所示:

https://localhost/supertext/api/v1/util/CountryList?{%22idList%22:[46,14,62,83,120]}

替代方案:

    $.ajax({
        dataType: "json",
        data: {
            idList: JSON.stringify(listOfIds),
        }          
        type: "GET",
        url: "api/v1/util/CountryList",
        success: function (result) {
            alert(result);
        }
    });

网址:

https://localhost/supertext/api/v1/util/CountryList?idList=%5B46%2C14%2C62%2C83%2C120%5D

这两种方法都不起作用。

我真的必须以字符串形式发送和接收它还是使用 POST?

最佳答案

不,不要尝试在 GET 请求中发送 JSON。将 JSON 与其他有主体的动词一起使用,例如 POST 和 PUT。

按照标准方式,用 [FromUri] 属性装饰你的 Action 参数:

public IList<Country> GetCountryList([FromUri] List<long> idList)
{
    ...
}

然后就触发AJAX请求:

$.ajax({
    url: 'api/v1/util/CountryList',
    type: 'GET',
    data: { idList: [1, 2, 3] },
    traditional: true,
    success: function (result) {
        console.log(JSON.stringify(result));
    }
});

进一步推荐您阅读有关 Web API 中的模型绑定(bind)如何工作的内容:

http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-1

https://stackoverflow.com/questions/14628576/

相关文章:

java - 如何从 JSON 对象中获取日期

java - Spring MVC Controller 中的JSON参数

c# - 如何将 IEnumerable 转换为 JSON?

python - 将 JSON 日期字符串转换为 Python 日期时间

java - 我如何反序列化以 jackson 为单位的时间戳?

c# - 在 JSON.NET 中序列化/反序列化字节数组

json - 使用绝对或相对路径在 curl 请求中发送 json 文件

java - 使用 gson 反序列化对象的特定 JSON 字段

java - 对象序列化为 JSON(使用 Gson)。如何在 UpperCamelCase 中设置

ruby - 将不间断空格转换为 Ruby 中的空格