Thursday, September 15, 2011

Creating an ActionResult whch returns XML with ASP.NET MVC

In the past, with Webforms, whenever I needed a page to return a pure XML document to the browser I used to do like this:


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


but when it came to doing the same thing with ASP.NET MVC it just didn’t seem right. 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()
{
Element 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:









Now you only have to use it further the cool action result!