我正在尝试发布以下请求,但收到"Unsupported Media Type"
响应。我将Content-Type
设置为application/json
。任何帮助将不胜感激。
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);
}
}
答案 0 :(得分:0)
在检查了从我的代码发送来的原始数据之后,我看到此行正在添加字符集:
var stringContent = new StringContent(json, UnicodeEncoding.UTF8, "application/json");
发送的实际数据如下:
Content-Type: application/json; charset=utf-8
我需要使用以下命令从请求中删除字符集:
stringContent.Headers.ContentType.CharSet = string.Empty;