要使用ASP.Net返回具有正确编码的XML文档的XNode,可以使用以下代码示例:
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Web;
using System.Web.Mvc;
public class XmlResult : ActionResult
{
private readonly XNode _xml;
public XmlResult(XNode xml)
{
_xml = xml;
}
public override void ExecuteResult(ControllerContext context)
{
var response = context.HttpContext.Response;
response.ContentType = "application/xml";
using (var writer = new XmlTextWriter(response.Output))
{
writer.Formatting = Formatting.Indented;
writer.Indentation = 4;
_xml.WriteTo(writer);
}
}
}
然后,您可以在控制器中使用此结果类来返回具有正确编码的XML文档:
public class HomeController : Controller
{
public ActionResult Index()
{
XDocument xmlDoc = new XDocument(
new XElement("Root",
new XElement("Element1", "Value1"),
new XElement("Element2", "Value2")));
return new XmlResult(xmlDoc);
}
}
在上面的示例中,XmlResult
类继承自 ActionResult
类,并重写了 ExecuteResult
方法。在 ExecuteResult
方法中,我们设置了响应的内容类型为 application/xml
,然后将 XML 写入输出流中,以确保正确的编码。