Web Service 或 WCF调用时读取 XML 数据时,超出最大字符串内容长度配额(8192)解决方法
1.调用服务时服务
当我们使用 Web Service 或 WCF 服务时,常把读取的数据转化为string类型(xml格式),当数据量达到一 定数量时,会出现以下异常:
错误:格式化程序尝试对消息反序列化时引发异常: 尝试对参数 http://tempuri.org/ (命名空间)进行反序列化时出错: InnerException 消息是“反序列化对象异常,读取 XML 数据时,超出最大字符串内容长度配额 (8192)。通过更改在创建 XML 读取器时所使用的 XmlDictionaryReaderQuotas 对象的 MaxStringContentLength 属性,可增加此配额。
2.原因及解决方案
WCF传输大数据时,因为WCF本身的安全机制导致的,限制了客户端与服务器资源传输大小,当传输的数据超过上限后会产生异常。
发送大数据:在WCF服务端解决
NetTcpBinding binding = new NetTcpBinding();
binding.MaxReceivedMessageSize= 2147483647(更改这个数字) ;
接收大数据:在WCF客户端解决
NetTcpBinding binding = new NetTcpBinding();
binding.ReaderQuotas = new XmlDictionaryReaderQuotas()
{ MaxStringContentLength = 2147483647(更改这个数字) };
Web Service 调用时,在绑定代理端是,添加如下BasicHttpBinding:
有两种方法处理:
第一种:在调用时传入Binding参数。
BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.None) { MaxReceivedMessageSize = int.MaxValue, MaxBufferSize = int.MaxValue, ReaderQuotas = new System.Xml.XmlDictionaryReaderQuotas() { MaxStringContentLength = 2147483647 } } DLTEST.ServiceReference2.CS_WebServiceSoapClient svs = new DLTEST.ServiceReference2.CS_WebServiceSoapClient(binding);
第二种方法,改一下调用客户端的配置文件app.config
增加binding节点下增加 readerQuotas节点控制
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="CS_WebServiceSoap" >
<readerQuotas maxDepth="64" maxStringContentLength="8192000" maxArrayLength="16384000"
maxBytesPerRead="4096000" maxNameTableCharCount="16384000" />
</binding>
<binding name="CS_WebServiceSoap1" >
<readerQuotas maxDepth="64" maxStringContentLength="8192000" maxArrayLength="16384000"
maxBytesPerRead="4096000" maxNameTableCharCount="16384000" />
</binding>
<binding name="CS_WebServiceSoap2" />
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://10.0.0.251:100/WebService/CS_WebService.asmx"
binding="basicHttpBinding" bindingConfiguration="CS_WebServiceSoap"
contract="ServiceReference1.CS_WebServiceSoap" name="CS_WebServiceSoap" />
<endpoint address="http://localhost:90/WebService/CS_WebService.asmx"
binding="basicHttpBinding" bindingConfiguration="CS_WebServiceSoap1"
contract="ServiceReference2.CS_WebServiceSoap" name="CS_WebServiceSoap1" />
<endpoint address="http://localhost:3383/WebService/CS_WebService.asmx"
binding="basicHttpBinding" bindingConfiguration="CS_WebServiceSoap2"
contract="ServiceReference3.CS_WebServiceSoap" name="CS_WebServiceSoap2" />
</client>
</system.serviceModel>
</configuration>
作者: 王春天 出处: http://www.cnblogs.com/spring_wang/ Email: spring_best@yeah.net QQ交流:903639067
QQ群:322581894 关于作者: 大连天翼信息科技有限公司 技术总监。 SNF快速开发平台 创始人。应用平台架构师、IT规划咨询专家、业务流程设计专家。 专注于快速开发平台的开发、代码生成器。同时专注于微软平台项目架构、管理和企业解决方案,多年项目开发与管理经验,精通DotNet系列技术Vue、.NetCore、MVC、Webapi、C#、WinForm等,DB(SqlServer、Oracle等)技术,移动端开发。熟悉Java、VB及PB开发语言。在面向对象、面向服务以及数据库领域有一定的造诣。现从事项目实施、开发、架构等工作。并从事用友软件产品U8、U9、PLM 客开工作。 如有问题或建议,请多多赐教! 本文版权归作者和CNBLOGS博客共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,如有问题,可以通过邮箱或QQ 联系我,非常感谢。