views:

3573

answers:

3

What is the best way to return XML from a controller's action in ASP.NET MVC? There is a nice way to return JSON, but not for XML. Do I really need to route the XML through a View, or should I do the not-best-practice way of Response.Write-ing it?

+25  A: 

Use MVCContrib's XmlResult Action.

For reference here is their code:

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);
        }
    }
}
Luke Smith
The class here is taken straight from the MVC Contrib project. Not sure if thats what qualifies as rolling your own.
Sailing Judo
Where would you put this class, if you're following the ASP.NET MVC convention? Controllers folder? Same place you'd put your ViewModels, perhaps?
p.campbell
@pcampbel, I prefer creating separate folders in my project root for every kind of classes: Results, Filters, Routing, etc.
Anton
+11  A: 

There is a XmlResult (and much more) in MVC Contrib. Take a look at http://www.codeplex.com/MVCContrib

Mahdi
+4  A: 

If you are only interested to return xml through a request, and you have your xml "chunk", you can just do (as an action in your controller):

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