Return XML from a controller's action in as an ActionResult?
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); } }}
If you're building the XML using the excellent Linq-to-XML framework, then this approach will be helpful.
I create an XDocument
in the action method.
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);}
This reusable, custom ActionResult
serialises the XML for you.
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); }}
You can specify a MIME type (such as application/rss+xml
) and whether the output should be indented if you need to. Both properties have sensible defaults.
If you need an encoding other than UTF8, then it's simple to add a property for that too.