2013-03-12 4 views
19

私は、XMLデータを返す必要がありますウェブAPIメソッドを持っていますが、それは文字列を返します。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は、「コンテンツ」をサポートしていない場合:私はWebApiConfigクラスに以下のコードをもを追加した

[HttpGet] 
     public ActionResult Index() 
     { 
      var healthCheckReport = new HealthCheckReport(); 

      return Content(healthCheckReport.ToXml(), "text/xml"); 
     } 

config.Formatters.Remove(config.Formatters.JsonFormatter); 
config.Formatters.XmlFormatter.UseXmlSerializer = true; 
+1

あなただけHealthCheckReportインスタンスを返し、XMLフォーマッタシリアル化をやらせることができます?今は、コントローラのXMLにシリアル化してから、その文字列をXMLフォーマッタに渡しています。 XMLフォーマッタは、文字列をXMLにシリアル化します。 –

答えて

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

が、supporにHttpContentから派生した新しいXmlContentクラスを構築するためにも非常に簡単です。 t 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; 
    } 
} 

、あなたはそれがXmlDocumentオブジェクトを受け入れることを除いて、StreamContentまたはStringContentを使用するのと同じようにあなたがそれを使用することができ、

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

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

XmlContentクラスはどのように使用されますか?それはどこかに登録しなければなりませんか? –

関連する問題