通过GET传递一个JSON数组MVC的Web API [英] Passing an JSON array to MVC Web API via GET

查看:209
本文介绍了通过GET传递一个JSON数组MVC的Web API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有吨这个话题的答案,但无法找到解决我的问题。
我有一个ASP.NET MVC的Web API,它看起来像这样:

I know there are tons of answers for this topic, but couldn't find the solution to my issue. I have an ASP.NET MVC Web API that looks like this:

    [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,然后看起来是这样的:

The URL then looks like this:

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

这两种方法都不起作用。

Both methods don't work.

难道我真的要发送和接收它作为一个字符串或使用POST?

Do I really have to send and receive it as a string or use POST?

推荐答案

没有,不要试图在一个GET请求被发送JSON。使用JSON与具有身体其他动词,如POST和PUT。

No, don't try to be sending JSON in a GET request. Use JSON with other verbs which have body, such as POST and PUT.

做到这一点的标准方法,通过与 [FromUri] 属性装饰你的操作参数:

Do it the standard way, by decorating your action parameter with the [FromUri] attribute:

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

然后就触发AJAX请求:

and then just trigger the AJAX request:

$.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中的绑定是如何工作的:

Further recommended reading for you about how the model binding in the Web API works:

<一个href=\"http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-1\">http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-1

这篇关于通过GET传递一个JSON数组MVC的Web API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆