如何设置一个场景,其中一个托管在X的网站发布了一个URL,浏览后将返回纯粹的XML。
其他地方的网页会点击此网址,将XML加载到对象中。
所以我想要一个像http://www.xml.com/document.aspx?id=1
这样的网址另一个站点将使用webresponse和webrequest对象从上面的页面获取响应,我希望响应是好的XML,所以我可以使用XML来填充对象。
我确实得到了一些工作,但响应中包含了呈现页面所需的所有HTML,而我实际上只想要XML作为响应。
答案 0 :(得分:0)
可能最好的方法是使用HttpHandler / ASHX文件,但如果你想用一个页面来完成它是完全可能的。两个关键点是:
Response.ContentType = "text/xml"
如何生成XML本身取决于您,但如果XML表示对象图,则可以使用XmlSerializer
(来自System.Xml.Serialization
命名空间)将XML直接写入Response为你流,例如
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,您只需将其写入Response流,然后结束并刷新流。
// Set the ContentType
Response.ContentType = "text/xml";
Response.Write(myXmlString);
Response.Flush();
Response.End();