[英]receive and use HTTP Post JSON in C# asp.net
我有一个设备向云代理发布温度/ GPS数据。 然后,代理“HTTP将设备数据JSON对象发布到您选择的URL”(引自代理站点文档)。
如何在C#中接收和反序列化这篇文章? 我正在使用newtonsoft.json。 我在stackoverflow中看过一个类似的例子,但对我来说它创造了很多错误。 我的代码如下。 公共类Rootobject是通过粘贴JSON创建的,所以这一切都是自动的。 最终的部分是我不知道该怎么做(公共课测试部分)。 我不知道它到底在哪里,以及如何正确格式化它。
谢谢你的任何建议。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Http;
using Newtonsoft.Json;
namespace WebServiceTest1.Models
{
public class Rootobject
{
public DateTime received { get; set; }
public string authtype { get; set; }
public string[] tags { get; set; }
public Routingresults routingResults { get; set; }
public string device_name { get; set; }
public int errorcode { get; set; }
public string source { get; set; }
public string timestamp { get; set; }
public string record_id { get; set; }
public string data { get; set; }
public int device_id { get; set; }
}
public class Routingresults
{
public int matchedRules { get; set; }
public object[] errors { get; set; }
}
//This is the part I dont know where to put, or how to use properly.
public class Testing
{
string url = "http://example.com/MethodThatReturnsJson";
//I'm sure this needs to be the URL of the site that is POSTING.
WebClient client = new WebClient();
string webServiceJsonString = client.DownloadString(url);
//This line is erroring out. doesn't like client.DownloadString(url)
Rootobject yourObject = JsonConvert.DeserializeObject<Rootobject>(webServiceJsonString);
//I typed Rootobject here based on class Rootobject above, but not confident that is correct.
}
}
}
谢谢。
如果你只需要一个可以接受邮寄请求的控制器:
public class MyApiController : ApiController
{
public IHttpActionResult Post(Rootobject dto)
{
// do something...
return Ok();
}
}
如果您使用默认路由模板设置路由,这将接受对api/myapi
发布请求:
routes.MapHttpRoute(
name: "API Default",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.