尝试使用curl将json发送到WebAPI控制器方法时出错

本文关键字:WebAPI 控制器 方法 出错 curl json | 更新日期: 2023-09-27 18:17:40

我的控制器方法:

[HttpPost]
public void Post([FromBody] string vehicleDescriptors)
{
    var vehicles = JsonConvert.DeserializeObject<IList<VehicleDescriptorModel>>(vehicleDescriptors);
    MvcApplication.HubHelper.DataChanged(vehicles);
}

My json file contents:

{
  vehicleDescriptors:
    [
        {
            "Id":"A20940",
            "Type":"AUGER",
            "Organization":"OPERATIONS",
            "Office":"South Boston",
            "ReportedTimestamp":"''/Date(1406218241000)''/",
            "ReceivedTimestamp":"''/Date(1406218227000)''/",
            "Latitude":36.71,
            "Longitude":-78.9061,
            "Speed":0,
            "Heading":345,
            "Proximity":86978.617892562324
        }
    ]
}

我正在运行的curl语句:

curl "http://localhost/Web/api/vehicledescriptor/Post" -H "Content-Type: application/x-www-form-urlencoded" --data @vehicleDescriptors.json

我也试过了:

curl "http://localhost/Web/api/vehicledescriptor/Post" -H "Content-Type: application/json" --data @vehicleDescriptors.json

当它试图反序列化时,我得到这个错误,当我调试时,vehicleDescriptors参数为空:

{
"Message":"An error has occurred.",
"ExceptionMessage":"Value cannot be null. Parameter name: value",
"ExceptionType":"System.ArgumentNullException",
"StackTrace":"   at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)"
}

我在这里做错了什么?

尝试使用curl将json发送到WebAPI控制器方法时出错

基于L.B的帮助和我得到的一些尝试和错误,有几个问题:

  1. 正如L.B所说,反序列化是自动的,所以你的参数将作为反序列化对象通过
  2. json稍微偏离。如果可以的话,最好在代码中序列化对象并抓取,而不是尝试构建自己的对象:)
  3. curl命令很好,你需要使用application/json的内容类型头。

以下是工作版本:

[HttpPost]
public void Post([FromBody] List<VehicleDescriptorModel> vehicleDescriptors)
{
    MvcApplication.HubHelper.DataChanged(vehicleDescriptors);
}
json:

[
   {
      "Id":"A20940",
      "Type":"AUGER",
      "Organization":"OPERATIONS",
      "Office":"South Boston",
      "ReportedTimestamp":"''/Date(1406218241000)''/",
      "ReceivedTimestamp":"''/Date(1406218227000)''/",
      "Latitude":36.71,
      "Longitude":-78.9061,
      "Speed":0,
      "Heading":345,
      "Proximity":86978.617892562324
   }
]
旋度:

curl "http://localhost/Web/api/vehicledescriptor/Post" -H "Content-Type: application/json" --data @vehicleDescriptors.json