[英]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.