C# HttpClient POST or PUT Json with content type application/json

The HttpClient is a nifty tool for getting and sending data to a URL, but it works differently from the old fashioned WebRequest class.

The content type is added to the post data instead of added as a header parameter. So if you with to PUT or POST Json data, and you need to set the content type to application/json, specify the content type in the parameters of the StringContent that you POST:

string json;

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

An example of a complete POST method that can take an object and POST it as Json could look like this:

using System.Net.Http;
using Newtonsoft.Json;

private static HttpClient _httpClient = new HttpClient();

public bool POSTData(object json, string url)
{
  using (var content = new StringContent(JsonConvert.SerializeObject(json), System.Text.Encoding.UTF8, "application/json"))
  {
    HttpResponseMessage result = _httpClient.PostAsync(url, content).Result;
    if (result.StatusCode == System.Net.HttpStatusCode.Created)
      return true;
    string returnValue = result.Content.ReadAsStringAsync().Result;
    throw new Exception($"Failed to POST data: ({result.StatusCode}): {returnValue}");
  }
}

This method is not utilizing the async properties of the HttpClient class. Click here to see how to use HttpClient with async.

MORE TO READ:

Advertisements

About briancaos

Developer at Pentia A/S since 2003. Have developed Web Applications using Sitecore Since Sitecore 4.1.
This entry was posted in .net, .NET Core, c#, General .NET and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.