The formatter threw an exception while trying to deserialize the message in WCF

有一个WCF应用, 主要功能是存储doc, txt等类型文件到database,当文件的大小在16kb之内,调用WCF service能正常工作;但如果文件大小超出16KB之外, 它将抛出这样一个错误:

The remote server returned an unexpected response: (400) Bad Request.

经过在网上的查询, 需要在服务端添加配置maxReceivedMessageSize (可以参考这位朋友的文章http://www.cnblogs.com/Gyoung/p/3369316.html), 基于这位朋友发布的信息上,还需要注意定义binding name时需要与endpoint里的bindingConfiguration的名称一致,否则还是会出错。

<binding name="basicHttpBinding_IEmailUtility" closeTimeout="00:10:00" receiveTimeout="00:20:00" sendTimeout="00:20:00" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" openTimeout="00:10:00" messageEncoding="Mtom"/>

开始我使用的binding类型是basicHttpBinding, 添加之后,会出现另外一个错误:

The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter http://tempuri.org/:oneEmail. The InnerException message was 'There was an error deserializing the object of type EmailHelperWCF.EmailContent. The maximum array length quota (16384) has been exceeded while reading XML data. This quota may be increased by changing the MaxArrayLength property on the XmlDictionaryReaderQuotas object used when creating the XML reader. Line 1, position 237210.'.  Please see InnerException for more details.

解决办法:

1.  改变binding类型到WSHttpBinding

2.  在Binding下添加<readerQuotas maxStringContentLength="2147483647" maxArrayLength="2147483647">, 看下面的第三行

1 <wsHttpBinding>
2         <binding name="WSHttpBinding_IEmailUtility" closeTimeout="00:10:00" receiveTimeout="00:20:00" sendTimeout="00:20:00" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" openTimeout="00:10:00" messageEncoding="Mtom">
3           <readerQuotas maxDepth="32" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647"/>
4         </binding>
5   </wsHttpBinding>

3. 最好在<behaviors>下添加<dataContractSerializer maxItemsInObjectGraph="2147483647"/>, 看下面的第8行

 1  <behaviors>
 2       <serviceBehaviors>
 3         <behavior name="EmailHelperWCF.Service1Behavior">
 4           <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
 5           <serviceMetadata httpGetEnabled="true"/>
 6           <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
 7           <serviceDebug includeExceptionDetailInFaults="false"/>
 8           <dataContractSerializer maxItemsInObjectGraph="2147483647"/>
 9         </behavior>
10       </serviceBehaviors>
11 </behaviors>
原文地址:https://www.cnblogs.com/mystar/p/WCF.html