Search code examples
c#.netxmlashx

How do I display XML that has been posted to an ASHX handler on a page?


I am a new programmer working with C# and building a simple page, to which a third-party service posts XML. I would like to simply display this XML as text on a webpage.

I've started a new ASHX file that contains the following method:

public void ProcessRequest (HttpContext context) 
{

    StreamReader reader = new StreamReader(context.Request.InputStream);

    String xmlData = reader.ReadToEnd();
    XmlDocument doc = new XmlDocument();

    doc.LoadXml(xmlData);

    context.Response.ContentType = "text/xml";
    context.Response.Write(xmlData);

}

However, when the third-party application tries to post to the page, I get an error that the Root Element is missing.

If I understand this error correctly, this would seem to imply that the XML that was posted is not formatted correctly.

1.) If I am incorrect in this assumption, is there something wrong with the way that I am trying to receive and display the XML data using this handler?

2.) Otherwise, how might I easily troubleshoot by examining the contents of the XML that is sent to the service using my handler?


Solution

  • 1.) It's a good assumption, or the request is blank.

    The doc.LoadXml(xmlData); line will be where it's complaining about about a missing root element.

    2.) You could start by simply commenting out the above line, because you're not doing anything with the doc object yet.

    You might also need to set the content type to text/plain

    Longer term, you may want some try/catch logic around the LoadXml() call. Something like this perhaps...

    try
    {
        doc.LoadXml(xmlData);
        context.Response.ContentType = "text/xml";
        context.Response.Write(xmlData);
    }
    catch (Exception e)
    {
        context.Response.ContentType = "text/plain";
        context.Response.Write(e.Message);
    }