【问题标题】:POST dynamic content from one Web API service to another将动态内容从一个 Web API 服务发布到另一个
【发布时间】:2016-03-24 20:11:00
【问题描述】:

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

【问题讨论】:

    标签: c# .net asp.net-mvc-4 asp.net-web-api asp.net-web-api2


    【解决方案1】:

    你就快到了……

    根据我可以在您的问题中阅读的内容,以下内容应该适合您。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-30
      • 2017-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-15
      相关资源
      最近更新 更多