但是我只是 Response.Write 整个 XML 代码逐字写入,还是有更简洁的方式内置到 .NET 中?
您可以使用XmlWriter、XDocument甚至XmlSerializer来构建 XML,然后将其写入Response.OutputStream
.
这是一个带有的示例XDocument
:
public void ProcessRequest(HttpContext context)
{
var doc = new XDocument(
new XElement(
"messages",
new XElement(
"message",
new XAttribute("id", "1"),
new XAttribute("value", "message 1"),
),
new XElement(
"message",
new XAttribute("id", "2"),
new XAttribute("value", "message 2")
)
)
);
context.Response.ContentType = "text/xml";
using (var writer = XmlWriter.Create(context.Response.OutputStream))
{
doc.WriteTo(writer);
}
}
JSON的同样问题
You would use a Json serializer such as JavaScriptSerializer and then write it to the output stream:
public void ProcessRequest(HttpContext context)
{
var serializer = new JavaScriptSerializer();
string json = serializer.Serialize(new
{
messages = new[]
{
new { id = 1, value = "message 1" },
new { id = 2, value = "message 2" },
}
});
context.Response.ContentType = "application/json";
context.Response.Write(json);
}
This being said, you should be aware that ASP.NET MVC or the knocking on the door Web API are now the preferred ways to expose such data instead of writing generic handlers.