如何从一个Web API方法返回的XML数据? [英] How to return Xml Data from a Web API Method?

查看:94
本文介绍了如何从一个Web API方法返回的XML数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Web API方法应返回的XML数据,但它返回字符串:

 公共类HealthCheckController:ApiController
    {
        [HTTPGET]
        公共字符串指数()
        {
            VAR healthCheckReport =新HealthCheckReport();            返回healthCheckReport.ToXml();
        }
    }

返回的是:

 <字符串的xmlns =htt​​p://schemas.microsoft.com/2003/10/Serialization/>
< myroot><&MYNODE GT;< / MYNODE>< / myroot>
< /串>

和我加入这个映射:

  config.Routes.MapHttpRoute(
              名称:健康检查,
              routeTemplate:健康检查,
              默认:新
              {
                  控制器=健康检查,
                  行动=索引
              });

如何使它只返回XML位:

 < myroot><&MYNODE GT;< / MYNODE>< / myroot>

如果我只用MVC,我就可以用下面的,但网络API不支持内容:

  [HTTPGET]
        公众的ActionResult指数()
        {
            VAR healthCheckReport =新HealthCheckReport();            返回内容(healthCheckReport.ToXml(),文/ XML);
        }

我还增加了以下codeS到WebApiConfig类:

  config.Formatters.Remove(config.Formatters.JsonFormatter);
 config.Formatters.XmlFormatter.UseXmlSerializer =真;


解决方案

最快捷的方式是这样的,

公共类HealthCheckController:ApiController
 {
     [HTTPGET]
     公众的Htt presponseMessage指数()
     {
         VAR healthCheckReport =新HealthCheckReport();         返回新的Htt presponseMessage(){内容=新的StringContent(healthCheckReport.ToXml(),Encoding.UTF8,应用程序/ XML)};
     }
 }

但它也很容易建立,从HttpContent派生直接支持XmlDocument的或的XDocument一个新XmlContent类。例如

公共类XmlContent:HttpContent
{
    私人只读的MemoryStream _Stream =新的MemoryStream();    公共XmlContent(XmlDocument的文件){
        document.Save(_Stream);
            _Stream.Position = 0;
        Headers.ContentType =新MediaTypeHeaderValue(应用程序/ XML);
    }    保护覆盖任务SerializeToStreamAsync(流流,System.Net.TransportContext上下文){        _Stream.CopyTo(流);        VAR TCS =新TaskCompletionSource<对象>();
        tcs.SetResult(NULL);
        返回tcs.Task;
    }    保护覆盖布尔TryComputeLength(出长长度){
        长度= _Stream.Length;
        返回true;
    }
}

和您可以使用它,就像你会使用StreamContent或的StringContent,但它接受的XmlDocument,

公共类HealthCheckController:ApiController
{
    [HTTPGET]
    公众的Htt presponseMessage指数()
    {
       VAR healthCheckReport =新HealthCheckReport();       返回新的Htt presponseMessage(){
           RequestMessage =请求,
           内容=新XmlContent(healthCheckReport.ToXmlDocument())};
    }
}

I have a Web Api method which should return an xml data but it returns string:

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

            return healthCheckReport.ToXml();
        }
    }

It returns:

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
<myroot><mynode></mynode></myroot>
</string>

and I have added this mapping:

 config.Routes.MapHttpRoute(
              name: "HealthCheck",
              routeTemplate: "healthcheck",
              defaults: new
              {
                  controller = "HealthCheck",
                  action = "Index"
              });

How to make it return just the xml bits:

<myroot><mynode></mynode></myroot>

If I was using just MVC, I could be using the below but Web API doesn't support "Content":

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

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

I have also added the below codes to the WebApiConfig class:

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

解决方案

The quickest way is this,

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

         return new HttpResponseMessage() {Content = new StringContent( healthCheckReport.ToXml(), Encoding.UTF8, "application/xml" )};
     }
 }

but it is also very easy to build a new XmlContent class that derives from HttpContent to support XmlDocument or XDocument directly. e.g.

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

and you can use it just like you would use StreamContent or StringContent, except that it accepts a 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数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆