Question

How do I setup a scenario where one website hosted at X publishes a URL that when browsed to will return purely XML.

A web page elsewhere is going to hit this URL, load the XML into objects.

So I want a url like http://www.xml.com/document.aspx?id=1

Another site will use webresponse and webrequest objects to get the response from the above page, I want the response to be good XML so I can just use the XML to populate objects.

I did get something working but the response contained all the HTML required to render the page and I actually just want XML as the response.

Was it helpful?

Solution

Probably the best way to this is with a HttpHandler/ASHX file, but if you want to do it with a page it's perfectly possible. The two key points are:

  1. Use an empty page. All you want in the markup for your ASPX is the <% Page ... %> directive.
  2. Set the ContentType of the Response stream to XML - Response.ContentType = "text/xml"

How you generate the XML itself is up to you, but if the XML represents an object graph, you can use an XmlSerializer (from the System.Xml.Serialization namespace) to write the XML directly to the Response stream for you e.g.

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);

If you already have the XML, then once you've set the ContentType, you just need to write it to the Response stream and then end and flush the stream.

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

Response.Write(myXmlString);

Response.Flush();
Response.End();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top