How to return an XML string as an action result in MVC [duplicate]

旧巷老猫 提交于 2019-11-26 19:17:05

问题


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

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


回答1:


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




回答2:


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




回答3:


Another way to do this is by using XDocument:

using System.Xml.Linq;

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

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



回答4:


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

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

    return new XmlActionResult(xml);
}


来源:https://stackoverflow.com/questions/878695/how-to-return-an-xml-string-as-an-action-result-in-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!