【问题标题】:using web sites to transfer xml使用网站传输xml
【发布时间】:2012-10-23 20:25:34
【问题描述】:

我如何设置一个场景,其中托管在 X 上的一个网站发布一个 URL,当浏览该 URL 时将返回纯 XML。

其他地方的网页将访问此 URL,将 XML 加载到对象中。

所以我想要一个像http://www.xml.com/document.aspx?id=1这样的网址

另一个站点将使用 webresponse 和 webrequest 对象从上面的页面获取响应,我希望响应是好的 XML,所以我可以使用 XML 来填充对象。

我确实得到了一些工作,但响应包含呈现页面所需的所有 HTML,我实际上只是想要 XML 作为响应。

【问题讨论】:

标签: asp.net xml webresponse


【解决方案1】:

可能最好的方法是使用 HttpHandler/ASHX 文件,但如果您想使用页面来完成它,这是完全可能的。两个关键点是:

  1. 使用空白页。您在 ASPX 的标记中想要的只是 指令。
  2. 设置响应流的ContentType 到 XML - Response.ContentType = "text/xml"

如何生成 XML 本身取决于您,但如果 XML 表示对象图,您可以使用 XmlSerializer(来自 System.Xml.Serialization 命名空间)为您将 XML 直接写入响应流,例如

using System.Xml.Serialization;

// New up a serialiser, passing in the System.Type we want to serialize
XmlSerializer serializer = new XmlSerializer(typeof(MyObject));

// Set the ContentType
Response.ContentType = "text/xml";

// Serialise the object to XML and pass it to the Response stream 
// to be returned to the client
serialzer.Serialize(Response.Output, MyObject);

如果您已经拥有 XML,那么一旦设置了 ContentType,您只需将其写入响应流,然后结束并刷新流。

// Set the ContentType
Response.ContentType = "text/xml";

Response.Write(myXmlString);

Response.Flush();
Response.End();

【讨论】:

  • 好吧,我已经有了 XML,我只想将它作为字符串获取到另一端,没有幻想,只需通过 Internet 发送一个字符串,它将是 xml。干杯
  • 我很害怕,我看不到我如何使用它来发送字符串
  • @RobertHancliff 更新了有关输出简单 XML 字符串的信息
  • 别担心,我想根据你的想法,我已经设法写出了非常合适的东西。现在来消费它。支持 HTTPHandler 的想法,谢谢
猜你喜欢
  • 2011-09-21
  • 2018-01-30
  • 2011-04-10
  • 2011-08-19
  • 2017-05-29
  • 2015-04-11
  • 2019-06-13
  • 1970-01-01
  • 2012-03-22
相关资源
最近更新 更多