using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Xml.Serialization; namespace Disco.Web.Extensions { /// /// Action result that serializes the specified object into XML and outputs it to the response stream. /// /// people = _peopleService.GetPeople(); /// return new XmlResult(people); /// } /// ]]> /// /// public class XmlResult : ActionResult { private object _objectToSerialize; private XmlAttributeOverrides _xmlAttribueOverrides; /// /// Creates a new instance of the XmlResult class. /// /// The object to serialize to XML. public XmlResult(object objectToSerialize) { _objectToSerialize = objectToSerialize; } /// /// Creates a new instance of the XMLResult class. /// /// The object to serialize to XML. /// public XmlResult(object objectToSerialize, XmlAttributeOverrides xmlAttributeOverrides) { _objectToSerialize = objectToSerialize; _xmlAttribueOverrides = xmlAttributeOverrides; } /// /// The object to be serialized to XML. /// public object ObjectToSerialize { get { return _objectToSerialize; } } /// /// Serialises the object that was passed into the constructor to XML and writes the corresponding XML to the result stream. /// /// The controller context for the current request. public override void ExecuteResult(ControllerContext context) { if (_objectToSerialize != null) { var xs = (_xmlAttribueOverrides == null) ? new XmlSerializer(_objectToSerialize.GetType()) : new XmlSerializer(_objectToSerialize.GetType(), _xmlAttribueOverrides); context.HttpContext.Response.ContentType = "text/xml"; xs.Serialize(context.HttpContext.Response.Output, _objectToSerialize); } } } }