2013-03-12 53 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