У меня есть метод Web Api, который должен возвращать XML-данные, но возвращает строку:
public class HealthCheckController : ApiController
{
[HttpGet]
public string Index()
{
var healthCheckReport = new HealthCheckReport();
return healthCheckReport.ToXml();
}
}
Он возвращает:
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
<myroot><mynode></mynode></myroot>
</string>
и я добавил это отображение:
config.Routes.MapHttpRoute(
name: "HealthCheck",
routeTemplate: "healthcheck",
defaults: new
{
controller = "HealthCheck",
action = "Index"
});
Как заставить его возвращать только биты xml:
<myroot><mynode></mynode></myroot>
Если бы я использовал только MVC, я мог бы использовать ниже, но веб-API не поддерживает "Контент":
[HttpGet]
public ActionResult Index()
{
var healthCheckReport = new HealthCheckReport();
return Content(healthCheckReport.ToXml(), "text/xml");
}
Я также добавил следующие коды к классу WebApiConfig:
config.Formatters.Remove(config.Formatters.JsonFormatter);
config.Formatters.XmlFormatter.UseXmlSerializer = true;