简体   繁体   中英

Return XML as HTTP response

I've been given a seemingly simple task.

When a given URL is requested the response should simply be some valid XML.

How do I achieve this?

The URL will contain all the necessary code behind to get the data and construct the correct XML string. How do you then go ahead and manipulate the response to return this string only? The caller is receiving the XML string and populating a database with it, that's there responsibility I just need to provide this part of the project.

Thanks

Take a look at this :

Response.Clear();
Response.Write(yourXml);
Response.ContentType = "text/xml";
Response.End();

I would go for an HttpHandler. This way you circumvent all asp.net control creation etc. which is better for performance and seeing as you will not be outputting any html there's no point in using an actual aspx page.

Assuming you have your XML string created you can clear the response and just write your string out.

Response.Clear();
Response.ContentType = "text/xml";
Response.Write(myXMLString);

If you don't want to use full blown webservice then you could do something like this:

private void Page_Load(object sender, System.EventArgs e)
{

    Response.ContentType = "text/xml";

    //get data from somewhere...
    Response.Write(data);

  }
}

See here for something similar using images http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=325

Below is the way to send xml data to the browser as a response.

  StringBuilder xmlBuilder = new StringBuilder();

        xmlBuilder.Append("<Books>");
        xmlBuilder.Append("<Book>");
        xmlBuilder.Append("Maths");
        xmlBuilder.Append("</Book>");
        xmlBuilder.Append("</Books>");

        context.Response.ContentType = "text/xml";

        context.Response.BinaryWrite(Encoding.UTF8.GetBytes(xmlBuilder.ToString()));
        context.Response.End();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM