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); |
Thanks Daniel! Saved me some time 🙂
I was having this exact problem. Adding “application/json” to the constructor solved the issue. Thanks for the post!
We need a lot more ingithss like this!
Thanks Daniel!! Saved me lot of time.
Worked ! thanks mate 🙂
This solved my issue. Thank you!
Thanks dude! You saved me and mark!
Thanks a lot. Solved my issue.
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???
I don’t think I understand what you want to do.
Thanks alot.
Thank you!