Creating an ActionResult that returns XML with ASP.NET MVC

July 2, 2009

In the past, with Webforms, whenever I needed a page to return a pure XML document to the browser I’d end up doing it something like this copied from page to page:

Response.Clear();
Response.ContentType = "text/xml";
Response.Write(myXml.ToString());
Response.End();

Frankly, this is more than sufficient, but when it came to doing the same thing with ASP.NET MVC it just didn’t seem right. Is this “separation of concerns” thing getting to me? You wouldn’t implement this code in the View, and it seems inappropriate to handle this within a controller Action (though you could). How about an ActionResult?

MvcContrib.ActionResults.XmlResult

I was a bit surprised to find this wasn’t already built into the core ASP.NET MVC framework so I set out to create my own, and in turn, found out one exists in the MVC Contrib project.

The XmlResult class is very simple. It inherits ActionResult and overrides the ExecuteResult method, where the XML is serialized and outputted to the response stream. Here’s a stripped down copy of the MvcContrib implementation:

public class XmlResult : ActionResult
{
    private object _objectToSerialize;

    public XmlResult(object objectToSerialize)
    {
        _objectToSerialize = objectToSerialize;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        if (_objectToSerialize != null)
        {
            var xs = new XmlSerializer(_objectToSerialize.GetType());
            context.HttpContext.Response.ContentType = "text/xml";
            xs.Serialize(context.HttpContext.Response.Output, _objectToSerialize);
        }
    }
}

XmlResult in action

To make use of this, you merely have to return a new instance of an XmlResult object within your Controller action, passing it the object you want to be serialized to XML. Here’s how it would look if I were wanting to output a useless document created with the new magic that is System.Xml.Linq:

public ActionResult Index()
{
    XElement root = new XElement("root");
    root.Add(new XElement("element1"));
    root.Add(new XElement("element2"));
    root.Add(new XAttribute("attribute1", "a value"));
    return new XmlResult(root);
}

And, as expected, if this particular Controller Action was requested in your browser, you’d see the following result:

image

Stay tuned for a following post that will make further use of this cool action result!

blog comments powered by Disqus

About me

I'm a consultant with Headspring in Austin, TX. My passion is creating web-based applications that are well crafted and solve real problems for real people. Want to know more? Check out my about page.

WTF is all this code? I came here for food!

My wife made a new year's resolution to try out at least one new recipe each week. Want to know what she's been feeding me? resolutionfood.blogspot.com