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


当前回答

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

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

其他回答

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

在没有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);

上面的代码在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)

希望这对你有所帮助

我花了好几个小时才解出来。 但是@anthls anwser救了我的命。

var data = new StringContent(JsonConvert.SerializeObject(new
   {
      abc = "jsjs",
      xyz = "hhhh"
    }));
data.Headers.ContentType = new MediaTypeHeaderValue("application/json"); // <--
var response = await client.PostAsync(url, data);

我也遇到过同样的问题

var content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json"); 

gave

“400个坏请求”

单独序列化JsonObject并在StringContent()中传递字符串解决了我的问题,不需要设置Encoding。use UTF8分开。