【问题标题】:WCF Restful Webservice serializing Datatable as XMLWCF Restful Webservice 将 Datatable 序列化为 XML
【发布时间】:2013-05-11 19:24:45
【问题描述】:

我正在使用带有框架 4.0 的 WCF restful web 服务。我想将数据表序列化为 XML 并返回生成的 XML。我有这个工作,但我不禁觉得有更好的方法。

我最初开始做以下事情:

[WebGet(UriTemplate = "")]
public DataTable helloWorld()
{
    using (DataTable dt = new DataTable("Test"))
    {
        dt.Columns.Add("Message");
        dt.Rows.Add(dt.NewRow());
        dt.Rows[0]["Message"] = "Hello World";

        return dt;
    }
}

这给了我以下不良结果:

<DataTable xmlns="http://schemas.datacontract.org/2004/07/System.Data">
  <xs:schema id="NewDataSet" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns=""     xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
    <xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:MainDataTable="Test" msdata:UseCurrentLocale="true">
      <xs:complexType>
        <xs:choice minOccurs="0" maxOccurs="unbounded">
          <xs:element name="Test">
            <xs:complexType>
              <xs:sequence>
                <xs:element name="Message" type="xs:string" minOccurs="0"/>
              </xs:sequence>
            </xs:complexType>
          </xs:element>
        </xs:choice>
      </xs:complexType>
    </xs:element>
  </xs:schema>
  <diffgr:diffgram xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
    <DocumentElement xmlns="">
      <Test diffgr:id="Test1" msdata:rowOrder="0" diffgr:hasChanges="inserted">
        <Message>Hello World</Message>
      </Test>
    </DocumentElement>
  </diffgr:diffgram>
</DataTable>

经过一番修改,我想出了以下代码,这有点笨拙。有没有更好的办法?为什么我不能处理内存流?我有内存泄漏吗?

[WebGet(UriTemplate = "")]
public Stream helloWorld()
{
    WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";

    using (DataTable dt = new DataTable("Test"))
    {
        dt.Columns.Add("Message");
        dt.Rows.Add(dt.NewRow());
        dt.Rows[0]["Message"] = "Hello World";

        using (StringWriter sw = new StringWriter())
        {
            dt.WriteXml(sw, System.Data.XmlWriteMode.IgnoreSchema, false);

            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(sw.ToString()));
            return ms;

            //this fails for some reason
            //using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(sw.ToString())))
            //    return ms;
        }
    }
}

这段代码给了我想要的结果(我对根标签并不挑剔):

<DocumentElement>
  <Test>
    <Message>Hello World</Message>
  </Test>
</DocumentElement>

【问题讨论】:

  • 知道这是很久以前的事了...但是您找到更好的解决方案了吗?我目前面临着完全相同的问题,DataTable 也更加嵌套 =(

标签: c# wcf rest


【解决方案1】:

我建议使用WCF Data Services 来执行此操作。它们实现了OData 协议,这意味着它们旨在以一致且可移植的方式公开数据。可以对 JSON 或 XML 进行序列化。

样品:

  1. Beginner level.
  2. A more comprehensive explanation and sample.

【讨论】:

    【解决方案2】:

    我建议使用 DataContract 进行序列化:

    这是一个很好的教程:http://www.codeproject.com/Articles/105273/Create-RESTful-WCF-Service-API-Step-By-Step-Guide

    您创建一个合约接口,在其中定义所有必要的方法。

    在你的情况下是这样的:

    namespace MyProject.HelloWorld {
        [ServiceContract]
        public interface IHelloWorld {
            [OperationContract]
            [WebGet(UriTemplate="", ResponeFormat=WebMessageFormat.Xml)]
            HelloWorldResult helloWorld();
        }
    
        [DataContract()]
        public class HelloWorldResult {
            [DataMember]
            public String Message {get; set;}
        }
    }
    

    只需在 Service.svc 中实现接口 IHelloWorld 并返回 HelloWorldResult 类的新实例:

    public HelloWorldResult helloWorld() {
       return new HelloWorldResult() {
           Message = "Hello World!"
       };
    }
    

    但你必须告诉端点使用 IHelloWorld 服务契约作为契约(见教程:http://www.codeproject.com/Articles/105273/Create-RESTful-WCF-Service-API-Step-By-Step-Guide --> 步骤 6)

    希望对你有帮助

    干杯

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-05
      • 2013-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-28
      • 1970-01-01
      相关资源
      最近更新 更多