将动态内容从一个Web API服务POST到另一个



我正在使用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服务的最佳方式是什么?

你几乎到了。。。

下面这样的东西应该对你有效,根据需要我可以在你的问题中阅读。

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...
}

最新更新