AJAX MVC 操作调用中的 contentType 编码不正确

Incorrect encoding of contentType in AJAX Call for MVC Action

我正在尝试调用一个 AJAX 函数来传输一些 JSON data(大约 38Kb 大小),它将被转换到 Controller Action 中的 List<ModelClass> 上其他处理器。

(简化)AJAX 传输前的_oRecords 数据格式 - console.log(JSON.stringify(_oRecords));

[{{"sn":2208,"timeStampMarker":"","Id":0,"Data1":1,"Data2":2,"Data3":3},{"sn":2209,"timeStampMarker":"","Id":0,"Data1":1,"Data2":2,"Data3":3},{"sn":2210,"timeStampMarker":"","Id":0,"Data1":1,"Data2":2,"Data3":3},}]

(简化)控制器操作的数据格式 - F12 网络负载

records=%5B%7B%22sn%22%3A2208%2C%22timeStampMarker%22%3A%22%22%2C%22Id%22%3A0%2C%22Data1%22%3A1%2C%2Data2%22%3A2%2C%22Data3%22%3A3%7D%2C%7B%22 sn%22%3A2159%2C%22timeStampMarker%22%3A%22%22%2C%22Id%22%3A0%2C%22Data1%22%3A1%2C%2Data2%22%3A2%2C%22Data3%22%3A3%7D%2C%7B%22 sn%22%3A2159%2C%22timeStampMarker%22%3A%22%22%2C%22Id%22%3A0%2C%22Data1%22%3A1%2C%2Data2%22%3A2%2C%22Data3%22%3A3%7D%2C%7B%22

本质上,'[', '{', ',' 等特殊字符被 AJAX 调用的 contentType 选项错误编码。按照此 post,在配置 AJAX 调用后收到上述结果,如下所示:

Ajax 调用配置 - 查看

$.ajax({
    url: '../CSV/SaveDataFoo/',
    type: "POST",
    cache: false,
    contentType: "application/json; charset=utf-8",
    data: { records: JSON.stringify(_oRecords) },
    dataType: "json"
});

控制器

public JsonResult SaveDataFoo(List<DataModelClass> records)
{
     //Does some things with `records` List<T>

     return Json(null);
}

由于传输不正确,records 的计数为 [0](如预期)。我可以做任何其他 AJAX 配置或进一步操作 _oRecords 来解决这个问题吗?提前致谢!

这里有两件事...

  1. 要发送带有 jQuery 的 JSON 请求正文,请不要将数据嵌套在对象中。 jQuery 会将其视为 application/x-www-form-urlencoded

    $.ajax({
      url: "../CSV/SaveDataFoo/",
      method: "POST",
      contentType: "application/json",
      processData: false,
      data: JSON.stringify(_oRecords),
      dataType: "json"
    });
    
  2. 要告诉您的控制器操作从响应主体中解析数据,请使用 [FromBody] attribute

    public JsonResult SaveDataFoo([FromBody] List<DataModelClass> records)