XML Response包含API Response上的HTML编码

时间:2011-07-14 19:01:38

标签: xml wcf api httpwebrequest httpwebresponse

我创建了一个WCF服务,我正在根据请求传递流。客户端代码如下所示:

  FileInfo fo = new FileInfo("c:/Downloads/test.xml");
        StreamWriter wo = fo.CreateText();

        XmlDocument MyXmlDocument = new XmlDocument();
        MyXmlDocument.Load("C:/DataFiles/Integrations/RequestXML.xml");
        byte[] RequestBytes = Encoding.GetEncoding("iso-8859-1").GetBytes(MyXmlDocument.OuterXml);

        Uri uri = new Uri("http://localhost:63899/MyRESTServiceImpl.svc/Receive");

        HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(uri);

        Request.ContentLength = RequestBytes.Length;

        Request.Method = "POST";

        Request.ContentType = "text/xml";

        Stream RequestStream = Request.GetRequestStream();
        RequestStream.Write(RequestBytes, 0, RequestBytes.Length);
        RequestStream.Close();

        HttpWebResponse response = (HttpWebResponse)Request.GetResponse();
        StreamReader reader = new StreamReader(response.GetResponseStream());
        string r = reader.ReadToEnd();
        //XmlDocument ReturnXml = new XmlDocument();
        //ReturnXml.LoadXml(reader.ReadToEnd());
        response.Close();

        wo.Write(r);

现在,我想要做的就是处理请求,然后将XML返回给客户端进行测试。这是我的IMyRESTServiceImpl.cs和MyRESTServiceImpl.svc.cs代码:

[ServiceContract]
public interface IMyRESTServiceImpl
{
    [OperationContract]
    [WebInvoke(BodyStyle = WebMessageBodyStyle.Bare)]
    Stream Receive(Stream text);
}


public class MyRESTServiceImpl : IMyRESTServiceImpl
{

    public Stream Receive(Stream text)  
        {  
            string stringText = new StreamReader(text).ReadToEnd();  

            return text;
        }   

}

基本上发生的事情是API在字符串标签中将我的XML返回给我,并使用HTML编码为<和>标志(& gt;& lt;)。我需要它才能将XML完全按照发送的方式返回给我。我已经对它进行了调试,并且XML在服务器端保持不变,所以这是在发送回来时发生的。关于如何处理这个问题的任何想法?感谢。

1 个答案:

答案 0 :(得分:2)

您的实现没有编译 - 声明该方法返回Stream,但它返回String。如果以字符串形式返回,它将对XML字符进行编码;如果您不想编码,请将其作为Stream或XmlElement(或XElement)返回。

使用示例更新

这是为任意XML响应返回Stream的方法示例:

[WebGet]
public Stream GetXML()
{
    string theXml = @"<products>
  <product name=""bread"" price=""1.33">
    <nutritionalFacts>
      <servings>2</servings>
      <calories>150</calories>
      <totalFat>2</totalFat>
    </nutritionalFacts>
  </product>
  <product name=""milk"" price=""2.99">
    <nutritionalFacts>
      <servings>8</servings>
      <calories>120</calories>
      <totalFat>5</totalFat>
    </nutritionalFacts>
  </product>
</products>";
    WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
    MemoryStream result = new MemoryStream(Encoding.UTF8.GetBytes(theXml);
    return result;
}