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

In this post I demonstrate how you can PUT or POST 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 then 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 JsonSerializer or the external library JSON.Net by Newtonsoft, in the below we will be using JSON.Net:

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

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 JsonConvert to turn it into a message (string containing JSON) which we can use for putting or posting. Besides the serialisation it is the same as the previous example. If you want to POST rather than PUT, you can use PostAsync rather than PutAsync.

That is all!

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

Also, when you start using the HttpClient, maybe you will be writing some tests and stubbing the client soon - check my post out on how to do this here.