xml - 如何从 Web API 方法返回 Xml 数据?

标签 xml asp.net-mvc asp.net-web-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,我可以使用下面的,但 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;

最佳答案

最快的方法是这样,

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

关于xml - 如何从 Web API 方法返回 Xml 数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15366096/

相关文章:

jquery - getJson 未在外部计算机上的 IE 11 中运行

c# - .net web api 服务器中的静态变量

具有 Windows 身份验证的 ASP.NET Web API 自托管

java - 删除部分 XML 声明,编码 ="UTF-8"独立 ="yes"JAXB

android - 涟漪效应不会超过 ImageView

jquery - Asp.net Core,如何在 JQuery/Ajax 中将文件和模型发布到 Controller ?

asp.net-mvc - 寻找示例 global.asax.cs 文件以获取路由信息

xml - 使用xslt读取xml中的xml

java - 在 Java 中从 xml 获取值到 .properties 文件

asp.net-mvc - ASP.NET MVC MiniProfiler 和 EntityFramework 6 初始化