问题描述
发现.netWebService一个怪异的问题,看代码例如:[WebMethod]publicDataTableTest(){DataTabledt=newDataTable("tb1");returndt;}[WebMethod][XmlInclude(typeof(AClass))]publicobjectTest(){AClassc=newAClass();returnc;}
调用正常。[WebMethod]publicobjectTest(){DataTabledt=newDataTable("tb1");returndt;}
调用报错。System.InvalidOperationException:生成XML文档时出错。--->System.InvalidOperationException:类型System.Data.DataTable不能用在此上下文中。要将System.Data.DataTable用作参数、返回类型或者类或结构的成员,该参数、返回类型或成员必须声明为类型System.Data.DataTable(它不能是对象)。类型System.Data.DataTable的对象不能用在非类型化的集合如ArrayList中。在System.Xml.Serialization.XmlSerializationWriter.WriteTypedPrimitive(Stringname,Stringns,Objecto,BooleanxsiType)在Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write1_Object(Stringn,Stringns,Objecto,BooleanisNullable,BooleanneedType)在Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write17_ServiceResult(Stringn,Stringns,ServiceResulto,BooleanisNullable,BooleanneedType)在Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write46_ServiceResult(Objecto)在System.Xml.Serialization.XmlSerializer.Serialize(XmlWriterxmlWriter,Objecto,XmlSerializerNamespacesnamespaces,StringencodingStyle,Stringid)---内部异常堆栈跟踪的结尾---在System.Xml.Serialization.XmlSerializer.Serialize(XmlWriterxmlWriter,Objecto,XmlSerializerNamespacesnamespaces,StringencodingStyle,Stringid)在System.Xml.Serialization.XmlSerializer.Serialize(TextWritertextWriter,Objecto,XmlSerializerNamespacesnamespaces)在System.Web.Services.Protocols.XmlReturnWriter.Write(HttpResponseresponse,StreamoutputStream,ObjectreturnValue)在System.Web.Services.Protocols.WebServiceHandler.WriteReturns(Object[]returnValues)在System.Web.Services.Protocols.WebServiceHandler.Invoke()为什么object为其他可序列化的类型数据都可以返回。有什么办法可以让它可以正常返回DataTable。别让我改方法返回类型。
解决方案
解决方案二:
基于SOAP协议的通讯,是不能使用父类引用的。SOAP协议,会将对对象序列化成XML传输——接收端,再将XML反序列化成对象。如果对象的类型不明确——这段XML将无法完成解析。如果想让你的方法通用:你可以用stringbyte[]——这些基础类型。
解决方案三:
[WebMethod]publicDataTablegetTableData(){SqlConnectionconn=newSqlConnection("server=localhost;database=data;uid=sa;pwd=sa");SqlDataAdapterda=newSqlDataAdapter("select*fromtable",conn);if(conn.State==ConnectionState.Closed){conn.Open();}DataTabledt=newDataTable();da.Fill(dt);if(conn.State==ConnectionState.Open){conn.Close();}returndt;}}
解决方案四:
会存在这个问题,具体原因未研究,可能是序列化的问题,datatable在类中存在时,直接序列化也是失败的。建议通过将表转换为xml文件的方式进行数据传输,如果都是。net开发就很简单了,否则调用端写下xml的解析函数就OKp_DtResult.WriteXml(p_Data_SetInfo.p_strResultPath,XmlWriteMode.WriteSchema);p_DtResult.ReadXml
解决方案五:
引用3楼zixingcheng_的回复:
会存在这个问题,具体原因未研究,可能是序列化的问题,datatable在类中存在时,直接序列化也是失败的。建议通过将表转换为xml文件的方式进行数据传输,如果都是。net开发就很简单了,否则调用端写下xml的解析函数就OKp_DtResult.WriteXml(p_Data_SetInfo.p_strResultPath,XmlWriteMode.WriteSchema);p_DtResult.ReadXml
目前就是这样操作,但是具体原因是什么?有点不能理解。也找不到任何相关资料。