【问题标题】:Rest API return response XML format, but same xml not get in result by using httpclientRest API 返回响应 XML 格式,但使用 httpclient 无法获得相同的 xml
【发布时间】:2020-12-06 11:22:06
【问题描述】:

我创建了返回 xml 格式响应的 web api。如下所示

<TXLife xmlns="http://ACORD.org/Standards/Life/2">
<TXLifeResponse>
  <TransRefGUID>61ec7f39-5744-410e-b601-dcd89d8d6f27</TransRefGUID>
  <TransType tc="510">Form Instance Update</TransType>
  <TransSubType tc="1022500310">Annuity Application for Mani ManiM</TransSubType>
  <TransExeDate>2016-08-25-04:00</TransExeDate>
  <TransExeTime>16:36:41.157-04:00</TransExeTime>
  <TransMode tc="2">Original</TransMode>
  <NoResponseOK tc="0"/>
  <TransResult>
     <ResultCode tc="3">Received Pending</ResultCode>
  </TransResult>

但是当使用 httpclient 调用 API 时,我收到了响应,但响应数据与上面不同,而是我得到了特殊字符的解码。

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">&lt;? 
xml version="1.0" encoding="utf-8"?&gt;
&lt;TXLife xmlns:acord="http://ACORD.org/Standards/Life/2"&gt;
&lt;TXLifeResponse&gt;
&lt;TransRefGUID&gt;dd8973e3-ac03-4690-908b- 
65da3d6a770f&lt;/TransRefGUID&gt;
&lt;TransType tc="510"&gt;Form Instance Update&lt;/TransType&gt;
&lt;TransSubType tc="1022500310"&gt;
      Annuity Application for  SUZANNE M PERSON&lt;/TransSubType&gt;
&lt;TransExeDate&gt;2020-08-17&lt;/TransExeDate&gt;
&lt;TransExeTime&gt;15:28:24Z&lt;/TransExeTime&gt;
&lt;TransMode tc="2"&gt;Original&lt;/TransMode&gt;
&lt;NoResponseOK tc="0" /&gt;
&lt;TransResult&gt;
  &lt;ResultCode tc="3"&gt;Received Pendinge&lt;/ResultCode&gt;
&lt;/TransResult&gt;
&lt;/TXLifeResponse&gt;
&lt;/TXLife&gt;</string>

我正在使用下面的代码来调用 API

       string response = string.Empty;
        using (var client = new HttpClient())
        {
            client.BaseAddress = parameters.DestinationUri;
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));             

            var responseTask = client.PostAsXmlAsync(parameters.DestinationUri, request);
            responseTask.Wait();

            var result = responseTask.Result;

            if (result.IsSuccessStatusCode)
            {
                response = result.Content.ReadAsStringAsync().Result;                    
            }

【问题讨论】:

    标签: api asp.net-mvc-4 asp.net-mvc-3 asp.net-web-api


    【解决方案1】:

    已解决。我只是在 API 响应中修复了。我返回 HttpResponseMessage 而不是返回字符串对象。 API 的变化如下所示

    string response = "response string info";
    
            return new HttpResponseMessage()
            {
                Content = new StringContent(response, Encoding.UTF8, "application/xml")
            };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-15
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多