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

时间:2014-08-11 13:05:09

标签: c# json curl asp.net-web-api

我的控制器方法:

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

    MvcApplication.HubHelper.DataChanged(vehicles);
}

我的json文件内容:

{
  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 "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参数为null:

{
"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)"
}

我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

基于L.B的帮助以及我到达那里的一些反复试验,有几个问题:

  1. 正如L.B所说,反序列化是自动化的,所以你的参数将作为反序列化的对象来实现
  2. json稍稍偏了。如果可以,最好在代码中序列化对象并获取它而不是尝试构建自己的对象:)
  3. curl命令很好,你需要使用application / json content-type header。
  4. 以下是工作版本:

    [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