Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing HttpClient to use Content-Type: text/xml

Tags:

c#

httpclient

This is driving me nuts, I am setting the ContentType header everywhere I can and can't seem to make it stop sending text/plain.

Watching the data in Fiddler, the request is always requesting:

POST http:/domain.com HTTP/1.1

Content-Type: text/plain; charset=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();
}
like image 880
Chad Grant Avatar asked Jun 06 '13 22:06

Chad Grant


3 Answers

It looks like you tried to hard :) This should just work.

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();
}
like image 126
outcoldman Avatar answered Oct 11 '22 21:10

outcoldman


Try settings the default request headers:

client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/xml"));
like image 31
Steve Andrews Avatar answered Oct 11 '22 19:10

Steve Andrews


Use "application/xml" instead of "text/xml"

like image 45
yayadavid Avatar answered Oct 11 '22 19:10

yayadavid