简体   繁体   English

将XML作为HTTP响应返回

[英]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. 当请求给定的URL时,响应应该只是一些有效的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. 该URL将包含所有必要的代码,以获取数据并构造正确的XML字符串。 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. 调用者正在接收XML字符串并使用它填充数据库,我只需要提供项目的这一部分。

Thanks 谢谢

Take a look at this : 看看这个 :

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

I would go for an HttpHandler. 我会选择一个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. 这样你就可以绕过所有asp.net控件创建等等,这对性能更好,因为你不会输出任何html,所以使用实际的aspx页面是没有意义的。

Assuming you have your XML string created you can clear the response and just write your string out. 假设您已创建XML字符串,则可以清除响应并将字符串写出来。

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: 如果您不想使用完整的Web服务,那么您可以执行以下操作:

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 使用图片查看此处的相似内容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. 以下是将xml数据作为响应发送到浏览器的方法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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