How to return Xml Data from a Web API Method? How to return Xml Data from a Web API Method? xml xml

How to return Xml Data from a Web API Method?


The quickest way is this,

 public class HealthCheckController : ApiController {            [HttpGet]     public HttpResponseMessage Index()     {         var healthCheckReport = new HealthCheckReport();         return new HttpResponseMessage() {Content = new StringContent( healthCheckReport.ToXml(), Encoding.UTF8, "application/xml" )};     } }

but it is also very easy to build a new XmlContent class that derives from HttpContent to support XmlDocument or XDocument directly. e.g.

public class XmlContent : HttpContent{    private readonly MemoryStream _Stream = new MemoryStream();    public XmlContent(XmlDocument document) {        document.Save(_Stream);            _Stream.Position = 0;        Headers.ContentType = new MediaTypeHeaderValue("application/xml");    }    protected override Task SerializeToStreamAsync(Stream stream, System.Net.TransportContext context) {        _Stream.CopyTo(stream);        var tcs = new TaskCompletionSource<object>();        tcs.SetResult(null);        return tcs.Task;    }    protected override bool TryComputeLength(out long length) {        length = _Stream.Length;        return true;    }}

and you can use it just like you would use StreamContent or StringContent, except that it accepts a XmlDocument,

public class HealthCheckController : ApiController{           [HttpGet]    public HttpResponseMessage Index()    {       var healthCheckReport = new HealthCheckReport();       return new HttpResponseMessage() {           RequestMessage = Request,           Content = new XmlContent(healthCheckReport.ToXmlDocument()) };    }}