[转载]WCF序列化65536大小限制的问题

错误:

The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter http://tempuri.org/:GetResult. The InnerException message was 'Maximum number of items that can be serialized or deserialized in an object graph is '65536'. Change the object graph or increase the MaxItemsInObjectGraph quota. '.  Please see InnerException for more details.

解决办法

  既然问题已经明确是WCF序列化和反序列化的65536大小限制导致Silverlight客户端接收不到,那就调整这个参数,异常信息已经给出提示可以配置MaxItemsInObjectGraph这个参数。我们修改Web.config即可:

以下是代码片段:
1: <configuration> 
2: <system.serviceModel> 

3: 

4: <serviceHostingEnvironment aspNetCompatibilityEnabled="true" 

5: multipleSiteBindingsEnabled="true" /> 

6: 

7: <!--设置 maxItemsInObjectGraph --> 

8: <services> 

9: 

10: <!--注意下面这个name属性,必须改成你自己的namespace+DomainService类名!! --> 

11: <service name="MyNamespace.MyDomainServiceClass" 

12: behaviorConfiguration="MyWCFConfig" /> 

13: </services> 

14: <behaviors> 

15: <serviceBehaviors> 

16: <behavior name="MyWCFConfig"> 

17: <dataContractSerializer maxItemsInObjectGraph="2147483647" /> 

18: </behavior> 

19: </serviceBehaviors> 

20: </behaviors> 

21: 

22: </system.serviceModel> 

23: </configuration> 

上面是最简单的配置方法,当然你的WCF如果很复杂,建议配置binding, endpoint等等

也可以通过编程的方式来解决,这需要在服务端和客户端进行设置:

服务端

ServiceHost host = new ServiceHost(serviceType, uri);
foreach (IServiceBehavior behavior in host.Description.Behaviors)
{
if (behavior is ServiceBehaviorAttribute)
{
(behavior as ServiceBehaviorAttribute).MaxItemsInObjectGraph = int.MaxValue;
}
}

客户端:

ChannelFactory<T> channelFactory = new ChannelFactory<T>(binding);
foreach (OperationDescription op in channelFactory.Endpoint.Contract.Operations)
{
DataContractSerializerOperationBehavior dataContractBehavior = op.Behaviors.Find<DataContractSerializerOperationBehavior>() as DataContractSerializerOperationBehavior;
if (dataContractBehavior != null)
{
dataContractBehavior.MaxItemsInObjectGraph = int.MaxValue;
}
}
原文地址:https://www.cnblogs.com/iack/p/3567239.html