簡體   English   中英

將動態內容從一種Web API服務發布到另一種

[英]POST dynamic content from one Web API service to another

我正在使用ASP.NET Web API2。在我的應用程序中,我需要將一些動態內容發布到另一個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服務發布到另一種異步方法的最佳方法是什么?

你快到了...

根據希望我能閱讀您的問題,類似以下內容的內容應該對您有用。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM