我有一个外部公司将数据推送到我们的服务器之一,他们将发送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.这是来自提琴手的原始数据.
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" }
Amy.. 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
在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