运维开发网

.net – 使用webapi中的HttpClient来使用xml

运维开发网 https://www.qedev.com 2020-06-11 12:33 出处:网络 作者:运维开发网整理
我使用WebClient从restfull服务(.net web api)获取Xml对象,一切都很好: using(WebClient client = new WebClient()) { client.Encoding = UTF8Encoding.UTF8; client.Headers[HttpRequestHeader.ContentType] = "text/xml";
我使用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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消