19
我有一個Web API方法應返回的XML數據,但它返回字符串:如何從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;
你能只返回HealthCheckReport實例,讓XML格式做系列化?現在,您在控制器中序列化爲XML,然後將該字符串傳遞給XML格式器。然後XML格式化程序將該字符串序列化爲XML。 – 2013-03-14 17:29:20