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;
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…