Chandra Bhattarai
Chandra Bhattarai

Reputation: 97

Unsupported media type in httpclient call c#

I'm a trying to post the following request but I am getting a "Unsupported Media Type" response. I am setting the Content-Type to application/json. Any help would be appreciated. And as per comment below, if i change content as 'new StringContent(JsonConvert.SerializeObject(root), Encoding.UTF8, "application/json")' then i get bad request response

string URL = "https://test.com/api/v2/orders/";  //please note it is dummy api endpoint
            var client = new HttpClient();
            var httpRequestMessage = new HttpRequestMessage
            {
                Method = HttpMethod.Post,
                RequestUri = new Uri(URL),
                Headers = {
                            { HttpRequestHeader.Authorization.ToString(), "Bearer ABcdwenlfbl8HY0aGO9Z2NacFj1234" },  //please note it is dummy bearer token
                            { HttpRequestHeader.Accept.ToString(), "application/json;indent=2" },
                            { HttpRequestHeader.ContentType.ToString(), "application/json" }
            },
                //Content =new StringContent(JsonConvert.SerializeObject(root), Encoding.UTF8, "application/json")
                Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(root))
            };
            var response = client.SendAsync(httpRequestMessage).Result;

Upvotes: 2

Views: 2617

Answers (1)

ProgrammingLlama
ProgrammingLlama

Reputation: 38727

With HttpClient, some headers are counted as request headers, and others are counted as content headers. I'm not sure why they made this distinction really, but the bottom line is that you have to add headers in the correct place.

In the case of Content-Type, this can be added as part of the StringContent constructor, or to the constructed StringContent object.

My approach is to use the constructor:

Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(root), System.Text.Encoding.UTF8, "application/json");

Or alternatively set it afterwards:

Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(root))
Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

Note: If your issue still presents after making this change, then it's likely a server-side problem and you'll need to contact the maintainer of the API to ask what you're doing wrong.

Upvotes: 3

Related Questions