如何在ASP.NET web api中接收json?

时间:2015-12-02 17:46:30

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

我有一家外部公司将数据推送到我们的服务器之一,他们将发送JSON数据。我需要创建一个POST api来接收它。这就是我到目前为止所拥有的

[System.Web.Http.HttpPost]
[System.Web.Http.ActionName("sensor")]
public void PushSensorData(String json)
{
    string lines = null;
    try
    {
          System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt");
          file.WriteLine(json);
          file.Close();
          //JSONUtilities.deserialize(json);
    }
    catch (Exception ex)
    {
        MobileUtilities.DoLog(ex.StackTrace);
    }
}

我通过使用fiddler发送json数据来测试它,但json为null。 这是来自fiddler的原始数据。

POST http://localhost:31329/mobileapi/pushsensordata/ HTTP/1.1
User-Agent: Fiddler
Host: localhost:31329
Content-Type: application/json
Content-Length: 533

{
"id": {
    "server": "0.test-server.mobi",
    "application": "test-server.mobi",
    "message": "00007-000e-4a00b-82000-0000000",
    "asset": "asset-0000",
    "device": "device-0000"
},
"target": {
    "application": "com.mobi"
},
"type": "STATUS",
"timestamp": {
    "asset": 0000000
    "device": 00000000,
    "gateway": 000000,
    "axon_received_at": 00000,
    "wits_processed_at": 000000
},
"data_format": "asset",
"data": "asset unavailable"
}

3 个答案:

答案 0 :(得分:9)

在Web API中,您可以让框架为您完成大部分繁琐的序列化工作。首先修改你的方法:

[HttpPost]
public void PushSensorData(SensorData data)
{
    // data and its properties should be populated, ready for processing
    // its unnecessary to deserialize the string yourself.
    // assuming data isn't null, you can access the data by dereferencing properties:
    Debug.WriteLine(data.Type);
    Debug.WriteLine(data.Id);
}

创建一个类。为了帮助您入门:

public class SensorData 
{
    public SensorDataId Id { get; set; }
    public string Type { get;set; }
}

public class SensorDataId
{
    public string Server { get; set; }
}

此类的属性需要镜像JSON的结构。我留给你完成为你的模型添加属性和其他类,但正如所写,这个模型应该工作。应该抛出与您的模型不对应的JSON值。

现在,当您调用Web API方法时,您的传感器数据已经被反序列化。

有关详细信息,请参阅http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

答案 1 :(得分:2)

您的Web API模型需要与javascript请求对象相同

例如,

BACKEND_SERVICE_PORT

在Javascript中,您的请求对象和javascript调用应该是这样的

public class SomeRequest
    {

        public string data1{ get; set; }
        public string data2{ get; set; }
        public string data13{ get; set; }

    }

在javascript中发布url和requestObj

像这样访问Web API

 var requestObj = {
                "data1": data1,
                "data2": data2,
                "data3": data3,

            };

答案 2 :(得分:-1)

你有没有尝试过JSON.stringify(你的对象)(这是Javascript,但任何语言都有这种实用程序),然后再将它传递给你的web api?

我是否也可以在前面指出您的评论,说明您正在使用GET方法,因为您无法使用POST?你的计划应该小心,因为GET方法只能占用太多空间:如果你的对象变大,你将被迫使用POST,所以我建议你马上采取这种方法。 / p>