【问题标题】:How to return Xml Data from a Web API Method?如何从 Web API 方法返回 Xml 数据?
【发布时间】:2013-03-12 16:00:31
【问题描述】:

我有一个 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,我可以使用以下内容,但 Web 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。

标签: xml asp.net-mvc asp.net-web-api


【解决方案1】:

最快的方法是这样,

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

【讨论】:

  • XmlContent 类是如何使用的?它必须在某个地方注册吗?
猜你喜欢
  • 2020-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多