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

时间:2020-03-06 14:44:17  来源:igfitidea点击:

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

解决方案

使用MVCContrib的XmlResult操作。

供参考的是他们的代码:

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);
        }
    }
}

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

如果我们只想通过请求返回xml,并且xml为"块",则可以这样做(作为控制器中的操作):

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

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