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.
var json = JsonConvert.SerializeObject(request);
var stringContent = new StringContent(json, UnicodeEncoding.UTF8, "application/json");
MyResult result = new MyResult();
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(baseurl);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", base64ApiKey);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage Res = await client.PostAsync(method, stringContent);
if (Res.IsSuccessStatusCode)
{
var response = Res.Content.ReadAsStringAsync().Result;
result = JsonConvert.DeserializeObject<MyResult>(response);
}
}
After inspecting the raw data sent from my code, I saw that this line was adding the charset:
var stringContent = new StringContent(json, UnicodeEncoding.UTF8, "application/json");
The actual data sent looked like this:
Content-Type: application/json; charset=utf-8
I needed to remove the charset from the request with:
stringContent.Headers.ContentType.CharSet = string.Empty;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.