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

如何从Web API方法返回Xml数据?,第1张

概述我有一个Web Api方法,它应该返回一个xml数据,但它返回字符串: public class HealthCheckController : ApiController { [HttpGet] public string Index() { var healthCheckReport = new He 我有一个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派生出来直接支持Xmldocument或Xdocument的新的XmlContent类。例如

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

以上是内存溢出为你收集整理的如何从Web API方法返回Xml数据?全部内容,希望文章能够帮你解决如何从Web API方法返回Xml数据?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1116235.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-29
下一篇 2022-05-29

发表评论

登录后才能评论

评论列表(0条)

保存