XML响应包含API响应上的HTML编码
我创建了一个WCF服务,根据请求将流传递给该服务。客户端代码如下所示:XML响应包含API响应上的HTML编码,xml,wcf,api,httpwebrequest,httpwebresponse,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/Reques
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返回给客户机进行测试。下面分别是我的imyrestserviceinpl.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返回给我,并对
流
,但它返回的是字符串
。如果以字符串形式返回,它将对XML字符进行编码;如果不需要编码,请将其作为流或XmlElement(或XElement)返回
使用示例更新
这是一个为任意XML响应返回流的方法示例:
[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;
}
[WebGet]
公共流GetXML()
{
字符串theXml=@”
8.
120
5.
";
WebOperationContext.Current.OutgoingResponse.ContentType=“text/xml”;
MemoryStream结果=新的MemoryStream(Encoding.UTF8.GetBytes(theXml));
返回结果;
}
是的,但是如何将其作为流发送回去?这就是我遇到的问题。我在互联网上搜索了一个工作示例,但没有找到任何结果。使用字符串是我能够将XML发送回去的唯一方法。当尝试将其作为流发送回去时,客户端没有收到任何内容。我在回答中添加了一个示例