2013-03-12 55 views
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; 
+1

你能只返回HealthCheckReport实例,让XML格式做系列化?现在,您在控制器中序列化为XML,然后将该字符串传递给XML格式器。然后XML格式化程序将该字符串序列化为XML。 – 2013-03-14 17:29:20

回答

39

最快的方法是这样的,

public class HealthCheckController : ApiController 
{  
    [HttpGet] 
    public HttpResponseMessage Index() 
    { 
     var healthCheckReport = new HealthCheckReport(); 

     return new HttpResponseMessage() {Content = new StringContent(healthCheckReport.ToXml(), Encoding.UTF8, "application/xml")}; 
    } 
} 

,但它也很容易建立,从HttpContent派生到支承实新XmlContent类直接使用XmlDocument或XDocument。例如

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; 
    } 
} 

,你可以使用它,就像你会使用StreamContent或的StringContent,不同之处在于它接受的XmlDocument,

public class HealthCheckController : ApiController 
{  
    [HttpGet] 
    public HttpResponseMessage Index() 
    { 
     var healthCheckReport = new HealthCheckReport(); 

     return new HttpResponseMessage() { 
      RequestMessage = Request, 
      Content = new XmlContent(healthCheckReport.ToXmlDocument()) }; 
    } 
} 
+0

如何使用XmlContent类?它是否需要在某处注册? – 2013-06-11 20:52:42