【问题标题】:How to return an XML string as an action result in MVC [duplicate]如何在 MVC 中将 XML 字符串作为操作结果返回 [重复]
【发布时间】:2009-05-18 16:55:01
【问题描述】:

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

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

【问题讨论】:

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


【解决方案1】:

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

【讨论】:

【解决方案2】:

对于 JSON/XML,我编写了一个 XML/JSON Action Filter,它可以很容易地处理,而无需在您的动作处理程序中处理特殊情况(您似乎正在这样做)。

【讨论】:

  • 对于任何阅读这篇文章的人 - 一定要检查他的过滤器......它运作良好。为 aleemb +1 分享!
【解决方案3】:

另一种方法是使用 XDocument:

using System.Xml.Linq;

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

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

【讨论】:

  • MVC 4(可能还有早期版本)中的一些实验表明这里返回的 MIME 类型是 text/html
【解决方案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);
}

【讨论】:

    猜你喜欢
    • 2010-10-07
    • 2015-07-19
    • 2013-12-29
    • 1970-01-01
    • 2019-12-15
    • 1970-01-01
    • 1970-01-01
    • 2014-12-20
    • 2019-01-31
    相关资源
    最近更新 更多