C# - How to PUT or POST JSON using the HTTPClient in .Net core

In this post I demonstrate how you can POST or PUT JSON using the HTTPClient in C#. The simplest way to do this is using the StringContent object:

var content = new StringContent("{\"someProperty\":\"someValue\"}", Encoding.UTF8, "application/json");
var _httpClient = new HttpClient();
var result = await _httpClient.PutAsync("http://someDomain.com/someUrl", content); //or PostAsync for POST

You simply provide the StringContent object to the "PutAsync" or "PostAsync" method along with an URL and you have sent a request with a body containing JSON.

However it is rare that you have a JSON string already ready to be sent. Often you have an object that you wish to convert to JSON before sending it. Here you can use either the built in JavascriptSerializer or the external library JSON.Net by Newtonsoft, both are in the example below:

var myObject = new SomeObject
{
   SomeProperty = "someValue"
};

var objAsJson = new JavaScriptSerializer().Serialize(myObject);
//var objAsJson = JsonConvert.SerializeObject(myObject);
var content = new StringContent(objAsJson, Encoding.UTF8, "application/json");
var _httpClient = new HttpClient();
var result = await _httpClient.PutAsync("http://someDomain.com/someUrl", content); //or PostAsync for POST

In the above we instantiate the class SomeObject with the property "SomeProperty" and give it the value "someValue". We then use the serialiser to turn it into a string of JSON which we can use for putting or posting. Besides this it is the same as the previous example. If you wish to use JSON.Net (Newtonsoft) you can see how to do that in the comment in the code above and replace the line with JavaScriptSerializer.

I hope these were the code snippets you were looking for, if so or if not, leave a comment below!