我试图从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,但我在这一步上被挂断了。


当前回答

如果使用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())

其他回答

如果使用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())

上面的代码在vbnet:

dim FeToSend as new (object--> define class)

Dim client As New HttpClient
Dim content = New StringContent(FeToSend.ToString(), Encoding.UTF8,"application/json")
content.Headers.ContentType = New MediaTypeHeaderValue( "application/json" )
Dim risp = client.PostAsync(Chiamata, content).Result

msgbox(risp.tostring)

希望这对你有所帮助

在没有WebApi包的情况下,新版本的HttpClient将会是:

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

或者如果你想异步:

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

我没有足够的声誉来评论pomber的答案,所以我发布了另一个答案。使用pomber的方法,我不断收到来自我正在发布JSON请求的API的“400个坏请求”响应(Visual Studio 2017, . net 4.6.2)。最终问题被追踪到StringContent()产生的“Content-Type”报头不正确(参见https://github.com/dotnet/corefx/issues/7864)。

博士tl;

使用pomber's answer和额外的一行来正确设置请求的头部:

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

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

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