在Web API中使用HttpClient发布JsonObject

我试图从Web API使用HttpClient POST JsonObject 。 我不太清楚如何去解决这个问题,在代码示例中找不到太多东西。

以下是我到目前为止:

 var myObject = (dynamic)new JsonObject(); myObject.Data = "some data"; myObject.Data2 = "some more data"; HttpClient httpClient = new HttpClient("myurl"); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = httpClient.Post("", ???); 

我想我需要把我的JsonObject当成StreamContent来投放,但是我正在把这个步骤挂起来。

使用HttpClient的新版本,没有WebApi包,它将是:

 var content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json"); var result = client.PostAsync(url, content).Result; 

或者,如果你想要它async:

 var result = await client.PostAsync(url, content); 

最简单的方法是使用一个StringContent ,用JSON对象的JSON表示。

 httpClient.Post( "", new StringContent( myObject.ToString(), Encoding.UTF8, "application/json")); 

根据你的.Net版本,你也可以使用HttpClientExtensions.PostAsJsonAsync方法。

https://msdn.microsoft.com/en-us/library/system.net.http.httpclientextensions.postasjsonasync.aspx

如果使用Newtonsoft.Json:

 using Newtonsoft.Json; using System.Net.Http; using System.Text; public static class Extensions { public static StringContent AsJson(this object o) => new StringContent(JsonConvert.SerializeObject(o), Encoding.UTF8, "application/json"); } 

例:

 var httpClient = new HttpClient(); var url = "https://www.duolingo.com/2016-04-13/login?fields="; var data = new { identifier = "username", password = "password" }; var result = await httpClient.PostAsync(url, data.AsJson())