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);

12 thoughts on “415 Unsuported media type

  1. Rupal says:

    I want to send a post request wherein the url contains query string parameters which in turn serves as the data for the third party exposed API. What should I set StringContent as???

Leave a Reply

Your email address will not be published. Required fields are marked *