Problem
I’m trying to use HttpClient from Web API to POST a JsonObject. I’m not sure how to proceed and can’t seem to locate anything in the way of sample code.
Here’s what I’ve come up with thus far:
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("", ???);
I believe I need to cast my JsonObject as a StreamContent, but I’m having trouble doing so.
Asked by Mark
Solution #1
It would be: with the new version of HttpClient and without the WebApi package:
var content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json");
var result = client.PostAsync(url, content).Result;
Alternatively, if you want it to be asynchronous:
var result = await client.PostAsync(url, content);
Answered by pomber
Solution #2
The simplest method is to use a StringContent with your JSON object’s JSON representation.
httpClient.Post(
"",
new StringContent(
myObject.ToString(),
Encoding.UTF8,
"application/json"));
Answered by carlosfigueira
Solution #3
You might alternatively use the HttpClientExtensions.PostAsJsonAsync method, depending on your.NET version.
Answered by user3285954
Solution #4
If using 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");
}
Example:
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())
Answered by Matthew Steven Monkan
Solution #5
I don’t have enough reputation to remark on pomber’s answer, so I’m going to post another one. I kept getting a “400 Bad Request” answer from an API I was POSTing my JSON request to using pomber’s method (Visual Studio 2017, .NET 4.6.2). The issue was eventually identified down to an improper “Content-Type” header provided by StringContent() (see https://github.com/dotnet/corefx/issues/7864).
tl;dr
To appropriately set the header on the request, use pomber’s answer with an extra line:
var content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json");
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var result = client.PostAsync(url, content).Result;
Answered by anthls
Post is based on https://stackoverflow.com/questions/6117101/posting-jsonobject-with-httpclient-from-web-api