强制HttpClient使用Content-Type:text / xml

时间:2013-06-06 22:49:15

标签: c# httpclient

这让我疯了,我在任何地方设置ContentType标头,似乎无法让它停止发送text / plain。

在Fiddler中观察数据时,请求总是在请求:

POST http:/domain.com HTTP / 1.1

Content-Type:text / plain;字符集= UTF-8

using (var httpClient = new HttpClient())
{
    var request = new HttpRequestMessage(HttpMethod.Post, "http://domain.com");
        request.Content = new StringContent(Serialize(obj), Encoding.UTF8, "text/xml");
        request.Content.Headers.Clear();
        request.Content.Headers.ContentType = new MediaTypeHeaderValue("text/xml");
        request.Headers.Clear();
        request.Headers.Add("Content-Type","text/xml");
        var response = await httpClient.SendAsync(request);
        return  await response.Content.ReadAsStringAsync();
}

3 个答案:

答案 0 :(得分:22)

看起来你试图努力:)这应该可行。

using (var httpClient = new HttpClient())
{
    var request = new HttpRequestMessage(HttpMethod.Post, "http://domain.com");
    request.Content = new StringContent(Serialize(obj), Encoding.UTF8, "text/xml");
    var response = await httpClient.SendAsync(request);
    return  await response.Content.ReadAsStringAsync();
}

答案 1 :(得分:9)

尝试设置默认请求标头:

client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/xml"));

答案 2 :(得分:4)

使用“application / xml”代替“text / xml”