如何 post json 对象数组到网络 api

how to post json object array to a web api

我怎样才能 post 一个 JSON 数组到 Web API?它适用于单个对象。

这是我试过的方法,但控制器似乎返回 0 而不是预期的 3

这是我的 JSON:

var sc = [{
              "ID": "5",
              "Patient_ID": "271655b8-c64d-4061-86fc-0d990935316a",
              "Table_ID": "Allergy_Trns",
              "Checksum": "-475090533",
              "LastModified": "2015-01-22T20:08:52.013"
          },
          {
              "ID": "5",
              "Patient_ID": "271655b8-c64d-4061-86fc-0d990935316a",
              "Table_ID": "Allergy_Trns",
              "Checksum": "-475090533",
              "LastModified": "2015-01-22T20:08:52.013"
          },
          {
              "ID": "5",
              "Patient_ID": "271655b8-c64d-4061-86fc-0d990935316a",
              "Table_ID": "Allergy_Trns",
              "Checksum": "-475090533",
              "LastModified": "2015-01-22T20:08:52.013"
          }];           

AJAX 来电:

$.ajax({
           url: urlString,
           type: 'POST',
           data: sc,
           dataType: 'json',
           crossDomain: true,
           cache: false,
           success: function (data) { console.log(data); }
        });

Web API 控制器:

[HttpPost]
public string PostProducts([FromBody]List<SyncingControl> persons)
{
    return persons.Count.ToString(); // 0, expected 3
}

有误 json Table_ID": "Allergy_Trns" 应该是 "Table_ID": "Allergy_Trns".

缺少双引号。

更新

您需要确保以 json 的形式发送参数,如下所示:

 $.ajax({
        url: urlString,
        type: 'POST',
        data: JSON.stringify(sc),
        dataType: 'json',
        contentType: 'application/json',
        crossDomain: true,
        cache: false,
        success: function (data) { console.log(data); }
    });

请注意 JSON.stringify(sc),@herbi 在指定内容类型方面也部分正确。

屏幕抓取

您必须将 content-type header 添加到 ajax 请求,以便 WebAPI 能够理解请求并使用正确的格式化程序反序列化数据:

$.ajax({
           url: urlString,
           type: 'POST',
           data: sc,
           dataType: 'json',
           contentType: "application/json",
           crossDomain: true,
           cache: false,
           success: function (data) { console.log(data); }
        });

您可以在 beforeSend 上设置 Content-Type,这将确保您的 json 数据与您的服务器对象匹配

$.ajax({
        beforeSend: function (xhr) {
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        },
           url: urlString,
           type: 'POST',
           data: sc,
           dataType: 'json',
           contentType: "application/json",
           crossDomain: true,
           cache: false,
           success: function (data) { console.log(data); }
        });