我正在使用ASP.NET Web API 2.从我的应用程序中,我需要将一些动态内容发布到其他Web API服务。目标服务需要此格式的数据。
public class DataModel
{
public dynamic Payload { get; set; }
public string id { get; set; }
public string key { get; set; }
public DateTime DateUTC { get; set; }
}
我正在考虑使用这样的东西:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:9000/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
dynamic payLoad = new ExpandoObject();
DataModel model = new DataModel();
model.Payload = payLoad;
var response = await client.PostAsJsonAsync(url, model);
}
以异步方式将动态信息从一个Web API服务发布到另一个Web API服务的最佳方法是什么?
答案 0 :(得分:0)
你差不多......
以下内容适用于您,根据我的想法,我可以阅读您的问题。
using (var client = new HttpClient())
{
var url = new Uri("http://localhost:9000");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
dynamic payLoad = new ExpandoObject();
DataModel model = new DataModel { Payload = payLoad };
//Model will be serialized automatically.
var response = await client.PostAsJsonAsync(url, model);
//It may be a good thing to make sure that your request was handled properly
response.EnsureSuccessStatusCode();
//If you need to work with the response, read its content!
//Here I implemented the controller so that it sends back what it received
//ReadAsAsync permits to deserialize the response content
var responseContent = await response.Content.ReadAsAsync<DataModel>();
// Do stuff with responseContent...
}