Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return Xml Data from a Web API Method?

Tags:

I have a Web Api method which should return an xml data but it returns string:

 public class HealthCheckController : ApiController     {                [HttpGet]         public string Index()         {             var healthCheckReport = new HealthCheckReport();              return healthCheckReport.ToXml();         }     } 

It returns:

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/"> <myroot><mynode></mynode></myroot> </string> 

and I have added this mapping:

 config.Routes.MapHttpRoute(               name: "HealthCheck",               routeTemplate: "healthcheck",               defaults: new               {                   controller = "HealthCheck",                   action = "Index"               }); 

How to make it return just the xml bits:

<myroot><mynode></mynode></myroot> 

If I was using just MVC, I could be using the below but Web API doesn't support "Content":

 [HttpGet]         public ActionResult Index()         {             var healthCheckReport = new HealthCheckReport();              return Content(healthCheckReport.ToXml(), "text/xml");         } 

I have also added the below codes to the WebApiConfig class:

 config.Formatters.Remove(config.Formatters.JsonFormatter);  config.Formatters.XmlFormatter.UseXmlSerializer = true; 
like image 290
The Light Avatar asked Mar 12 '13 16:03

The Light


People also ask

How we can return XML from Web API?

If you don't want the controller to decide the return object type, you should set your method return type as System. Net. Http. HttpResponseMessage and use the below code to return the XML.

Can we return XML from REST API?

Data types that REST API can return are as follows: JSON (JavaScript Object Notation) XML.

How does Web API send XML data?

If you want to send XML data to the server, set the Request Header correctly to be read by the sever as XML. xmlhttp. setRequestHeader('Content-Type', 'text/xml'); Use the send() method to send the request, along with any XML data.


1 Answers

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()) };     } } 
like image 175
Darrel Miller Avatar answered Oct 23 '22 16:10

Darrel Miller