如何在MVC中将XML字符串作为操作结果返回

时间:2009-05-18 16:55:02

标签: .net xml asp.net-mvc actionresult

  

可能重复:
  What is the best way to return XML from a controller's action in ASP.NET MVC?

我能够将JSON和部分视图(html)作为有效的ActionResult返回,但是如何返回XML字符串?

4 个答案:

答案 0 :(得分:131)

您可以使用return this.Content(xmlString, "text/xml");从操作中返回构建的XML字符串。

答案 1 :(得分:7)

对于JSON / XML,我编写了一个XML/JSON Action Filter,这使得在不处理动作处理程序中的特殊情况(这就是你似乎正在做的事情)时很容易解决。

答案 2 :(得分:4)

另一种方法是使用XDocument:

using System.Xml.Linq;

public XDocument ExportXml()
{
    Response.AddHeader("Content-Type", "text/xml");

    return XDocument.Parse("<xml>...");
}

答案 3 :(得分:4)

如果您使用Linq-to-XML构建XML,则check out my answer here。它允许您编写如下代码:

public ActionResult MyXmlAction()
{
    var xml = new XDocument(
        new XElement("root",
            new XAttribute("version", "2.0"),
            new XElement("child", "Hello World!")));

    return new XmlActionResult(xml);
}