从控制器的操作中返回XML作为ActionResult?

时间:2008-09-25 18:01:13

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

从ASP.NET MVC中的控制器操作返回XML的最佳方法是什么?返回JSON有一种很好的方法,但不适用于XML。我是否真的需要通过View路由XML,还是应该采用Response.Write-it的非最佳实践方式?

11 个答案:

答案 0 :(得分:126)

return this.Content(xmlString, "text/xml");

答案 1 :(得分:111)

使用MVCContrib的XmlResult Action。

以下是他们的代码:

public class XmlResult : ActionResult
{
    private object objectToSerialize;

    /// <summary>
    /// Initializes a new instance of the <see cref="XmlResult"/> class.
    /// </summary>
    /// <param name="objectToSerialize">The object to serialize to XML.</param>
    public XmlResult(object objectToSerialize)
    {
        this.objectToSerialize = objectToSerialize;
    }

    /// <summary>
    /// Gets the object to be serialized to XML.
    /// </summary>
    public object ObjectToSerialize
    {
        get { return this.objectToSerialize; }
    }

    /// <summary>
    /// Serialises the object that was passed into the constructor to XML and writes the corresponding XML to the result stream.
    /// </summary>
    /// <param name="context">The controller context for the current request.</param>
    public override void ExecuteResult(ControllerContext context)
    {
        if (this.objectToSerialize != null)
        {
            context.HttpContext.Response.Clear();
            var xs = new System.Xml.Serialization.XmlSerializer(this.objectToSerialize.GetType());
            context.HttpContext.Response.ContentType = "text/xml";
            xs.Serialize(context.HttpContext.Response.Output, this.objectToSerialize);
        }
    }
}

答案 2 :(得分:30)

如果您使用优秀的Linq-to-XML框架构建XML,那么这种方法将会有所帮助。

我在动作方法中创建XDocument

public ActionResult MyXmlAction()
{
    // Create your own XDocument according to your requirements
    var xml = new XDocument(
        new XElement("root",
            new XAttribute("version", "2.0"),
            new XElement("child", "Hello World!")));

    return new XmlActionResult(xml);
}

这个可重用的自定义ActionResult为您序列化XML。

public sealed class XmlActionResult : ActionResult
{
    private readonly XDocument _document;

    public Formatting Formatting { get; set; }
    public string MimeType { get; set; }

    public XmlActionResult(XDocument document)
    {
        if (document == null)
            throw new ArgumentNullException("document");

        _document = document;

        // Default values
        MimeType = "text/xml";
        Formatting = Formatting.None;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        context.HttpContext.Response.Clear();
        context.HttpContext.Response.ContentType = MimeType;

        using (var writer = new XmlTextWriter(context.HttpContext.Response.OutputStream, Encoding.UTF8) { Formatting = Formatting })
            _document.WriteTo(writer);
    }
}

您可以指定MIME类型(例如application/rss+xml)以及是否需要缩进输出。这两个属性都有合理的默认值。

如果您需要UTF8以外的编码,那么为其添加属性也很简单。

答案 3 :(得分:24)

如果您只想通过请求返回xml,并且您拥有xml“chunk”,那么您可以这样做(作为控制器中的操作):

public string Xml()
{
    Response.ContentType = "text/xml";
    return yourXmlChunk;
}

答案 4 :(得分:17)

MVC Contrib中有一个XmlResult(以及更多)。看看http://www.codeplex.com/MVCContrib

答案 5 :(得分:5)

我最近必须为Sitecore项目执行此操作,该项目使用一种方法从Sitecore项及其子项创建XmlDocument,并将其作为文件从控制器ActionResult返回。我的解决方案:

public virtual ActionResult ReturnXml()
{
    return File(Encoding.UTF8.GetBytes(GenerateXmlFeed().OuterXml), "text/xml");
}

答案 6 :(得分:2)

最后设法得到这项工作,并认为我会记录这里是如何希望拯救他人的痛苦。

环境

  • VS2012
  • SQL Server 2008R2
  • .NET 4.5
  • ASP.NET MVC4(Razor)
  • Windows 7

支持的网页浏览器

  • FireFox 23
  • IE 10
  • Chrome 29
  • Opera 16
  • Safari 5.1.7(最后一个用于Windows?)

我的任务是在ui按钮上单击,在我的Controller上调用一个方法(带有一些参数),然后让它通过xslt转换返回一个MS-Excel XML。返回的MS-Excel XML将导致浏览器弹出“打开/保存”对话框。这必须适用于所有浏览器(如上所列)。

首先,我尝试使用Ajax并使用文件名的“download”属性创建动态Anchor, 但这只适用于5种浏览器中的3种(FF,Chrome,Opera)而不适用于IE或Safari。 尝试以编程方式触发锚点的Click事件以导致实际的“下载”时存在问题。

我最终做的是使用“隐形”IFRAME,它适用于所有5个浏览器!

所以这就是我提出的: [请注意,我绝不是一个html / javascript专家,只包括相关代码]

HTML(相关位片段)

<div id="docxOutput">
<iframe id="ifOffice" name="ifOffice" width="0" height="0"
    hidden="hidden" seamless='seamless' frameBorder="0" scrolling="no"></iframe></div>

JAVASCRIPT

//url to call in the controller to get MS-Excel xml
var _lnkToControllerExcel = '@Url.Action("ExportToExcel", "Home")';
$("#btExportToExcel").on("click", function (event) {
    event.preventDefault();

    $("#ProgressDialog").show();//like an ajax loader gif

    //grab the basket as xml                
    var keys = GetMyKeys();//returns delimited list of keys (for selected items from UI) 

    //potential problem - the querystring might be too long??
    //2K in IE8
    //4096 characters in ASP.Net
    //parameter key names must match signature of Controller method
    var qsParams = [
    'keys=' + keys,
    'locale=' + '@locale'               
    ].join('&');

    //The element with id="ifOffice"
    var officeFrame = $("#ifOffice")[0];

    //construct the url for the iframe
    var srcUrl = _lnkToControllerExcel + '?' + qsParams;

    try {
        if (officeFrame != null) {
            //Controller method can take up to 4 seconds to return
            officeFrame.setAttribute("src", srcUrl);
        }
        else {
            alert('ExportToExcel - failed to get reference to the office iframe!');
        }
    } catch (ex) {
        var errMsg = "ExportToExcel Button Click Handler Error: ";
        HandleException(ex, errMsg);
    }
    finally {
        //Need a small 3 second ( delay for the generated MS-Excel XML to come down from server)
        setTimeout(function () {
            //after the timeout then hide the loader graphic
            $("#ProgressDialog").hide();
        }, 3000);

        //clean up
        officeFrame = null;
        srcUrl = null;
        qsParams = null;
        keys = null;
    }
});

C#SERVER-SIDE(代码段) @Drew创建了一个名为XmlActionResult的自定义ActionResult,我为此修改了它。

Return XML from a controller's action in as an ActionResult?

我的控制器方法(返回ActionResult)

  • 将keys参数传递给生成XML的SQL Server存储过程
  • 然后通过xslt将XML转换为MS-Excel xml(XmlDocument)
  • 创建修改后的XmlActionResult的实例并返回它

    XmlActionResult result = new XmlActionResult(excelXML,“application / vnd.ms-excel”); string version = DateTime.Now.ToString(“dd_MMM_yyyy_hhmmsstt”); string fileMask =“LabelExport_ {0} .xml”;
    result.DownloadFilename = string.Format(fileMask,version); 返回结果;

@Drew创建的XmlActionResult类的主要修改。

public override void ExecuteResult(ControllerContext context)
{
    string lastModDate = DateTime.Now.ToString("R");

    //Content-Disposition: attachment; filename="<file name.xml>" 
    // must set the Content-Disposition so that the web browser will pop the open/save dialog
    string disposition = "attachment; " +
                        "filename=\"" + this.DownloadFilename + "\"; ";

    context.HttpContext.Response.Clear();
    context.HttpContext.Response.ClearContent();
    context.HttpContext.Response.ClearHeaders();
    context.HttpContext.Response.Cookies.Clear();
    context.HttpContext.Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);// Stop Caching in IE
    context.HttpContext.Response.Cache.SetNoStore();// Stop Caching in Firefox
    context.HttpContext.Response.Cache.SetMaxAge(TimeSpan.Zero);
    context.HttpContext.Response.CacheControl = "private";
    context.HttpContext.Response.Cache.SetLastModified(DateTime.Now.ToUniversalTime());
    context.HttpContext.Response.ContentType = this.MimeType;
    context.HttpContext.Response.Charset = System.Text.UTF8Encoding.UTF8.WebName;

    //context.HttpContext.Response.Headers.Add("name", "value");
    context.HttpContext.Response.Headers.Add("Last-Modified", lastModDate);
    context.HttpContext.Response.Headers.Add("Pragma", "no-cache"); // HTTP 1.0.
    context.HttpContext.Response.Headers.Add("Expires", "0"); // Proxies.

    context.HttpContext.Response.AppendHeader("Content-Disposition", disposition);

    using (var writer = new XmlTextWriter(context.HttpContext.Response.OutputStream, this.Encoding)
    { Formatting = this.Formatting })
        this.Document.WriteTo(writer);
}

基本上就是这样。 希望它能帮助别人。

答案 7 :(得分:1)

一个简单的选项,可让您使用流和所有return File(stream, "text/xml");

答案 8 :(得分:0)

这是一种简单的方法:

        var xml = new XDocument(
            new XElement("root",
            new XAttribute("version", "2.0"),
            new XElement("child", "Hello World!")));
        MemoryStream ms = new MemoryStream();
        xml.Save(ms);
        return File(new MemoryStream(ms.ToArray()), "text/xml", "HelloWorld.xml");

答案 9 :(得分:0)

使用XDocument的Save()方法的answer from Drew Noakes的小变体。

public sealed class XmlActionResult : ActionResult
{
    private readonly XDocument _document;
    public string MimeType { get; set; }

    public XmlActionResult(XDocument document)
    {
        if (document == null)
            throw new ArgumentNullException("document");

        _document = document;

        // Default values
        MimeType = "text/xml";
    }

    public override void ExecuteResult(ControllerContext context)
    {
        context.HttpContext.Response.Clear();
        context.HttpContext.Response.ContentType = MimeType;
        _document.Save(context.HttpContext.Response.OutputStream)
    }
}

答案 10 :(得分:0)

使用其中一种方法

    public ContentResult GetXml()
    {
        string xmlString  = "your xml data";
        return Content(xmlString, "text/xml");
    }

    public string GetXml()
    {
        string xmlString = "your xml data";
        Response.ContentType = "text/xml";
        return xmlString;
    }