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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/878695/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 12:43:11  来源:igfitidea点击:

How to return an XML string as an action result in MVC

.netxmlasp.net-mvcactionresult

提问by Toran Billups

Possible Duplicate:
What is the best way to return XML from a controller's action in ASP.NET MVC?

可能的重复:
从 ASP.NET MVC 中的控制器操作返回 XML 的最佳方法是什么?

I'm able to return JSON and partial views (html) as a valid ActionResult, but how would one return an XML string?

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

回答by John Downey

You could use return this.Content(xmlString, "text/xml");to return a built XML string from an action.

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

回答by aleemb

For JSON/XML I have written an XML/JSON Action Filterthat makes it very easy to tackle without handling special cases in your action handler (which is what you seem to be doing).

对于 JSON/XML,我编写了一个XML/JSON 动作过滤器,它可以很容易地处理,而无需在动作处理程序中处理特殊情况(这就是你似乎正在做的事情)。

回答by Levitikon

Another way to do this is by using XDocument:

另一种方法是使用 XDocument:

using System.Xml.Linq;

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

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

回答by Drew Noakes

If you're building the XML using Linq-to-XML then check out my answer here. It allows you to write code like this:

如果您使用 Linq-to-XML 构建 XML,请在此处查看我的答案。它允许您编写如下代码:

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

    return new XmlActionResult(xml);
}