415 Unsuported media type

A common error when posting JSON to a WebAPI service is "415 Unsupported Media Type". When posting JSON with HttpClient you added your JSON to StringContent and using Uri and StringContent as argument for PostAsync. The code below resulting in above mentioned error.

var content = new StringContent(json);
await client.PostAsync(uri, content);

The first thought is often to set content type on the HttpClient. But in this case it will not be the right solution.

It easy to miss that the StringContent constructor has two overloads that receives media type. The code below will make the error to disappear.

var content = new StringContent(json, Encoding.UTF8, "application/json");
await client.PostAsync(uri, content);

  4/22/2014 - 2:28 PM