gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 12:51:48 25 4
gpt4 key购买 nike

我知道这个主题有很多答案,但找不到我的问题的解决方案。我有一个如下所示的 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

关于jquery - 通过 GET 将 JSON 数组传递给 MVC Web API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14628576/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com