使用来自 webapi 的 HttpClient 使用 xml

Consuming xml using HttpClient from webapi

我使用 WebClient 从 restfull 服务 (.net web api) 获取了一个 Xml 对象,并且一切正常:

using(WebClient client = new WebClient())
{
   client.Encoding = UTF8Encoding.UTF8;
   client.Headers[HttpRequestHeader.ContentType] = "text/xml";
   client.Credentials = // ....;
   xmlResult = webClient.DownloadString(url);
}

....

此代码效果很好。我得到一个 Xml 作为字符串返回,每个人都很高兴。

现在,我更改了它,以便它可以与 HttpClient 一起使用,但我无法返回 Xml - 始终是 json 作为字符串。

using(var handler = new HttpClientHandler() {Credentials = new NetworkCredentials})
using(var client = new HttpClient(handler))
{
   var request = new HttpRequestMessage(HttpMethod.Get, url);
   request.Headers.Add(HttpRequestHeader.ContentType.ToString(), "text/xml");
   returnedXml = client.SendAsync(request).Result.Content.ReadAsStringAsync().Result;
}   

我做错了什么?怎样才能得到我向往的Xml?

谢谢

试试这个..

using(var handler = new HttpClientHandler() {Credentials = new NetworkCredentials})
using(var client = new HttpClient(handler))
{
      client.DefaultRequestHeaders
      .Accept
      .Add(new MediaTypeWithQualityHeaderValue("text/xml"));
   var request = new HttpRequestMessage(HttpMethod.Get, url);
    returnedXml = client.SendAsync(request).Result.Content.ReadAsStringAsync().Result;
}  

想通了!

我应该添加一个 Accept header,它的类型应该是 "application/xml"。

工作版本:

using(var handler = new HttpClientHandler() {Credentials = new NetworkCredentials})
using(var client = new HttpClient(handler))
{
  var request = new HttpRequestMessage(HttpMethod.Get, url);
  request.Headers.Add(HttpRequestHeader.Accept.ToString(), "application/xml");
  returnedXml = client.SendAsync(request).Result.Content.ReadAsStringAsync().Result;
}