Change MaxItemsInObjectGraph for a WCF Service

By Michael Detras

Sometimes, a WCF service operation may require or return some data that is complex and large that the DataContractSerializer may fail to serialize the data. We can change the MaxItemsInObjectGraph to a higher value to solve this.

If we are going to change this via a configuration file, we need to add a dataContractSerializer tag and set the maxItemsInObjectGraph.

<behavior name="defaultServiceBehavior">          
  <serviceMetadata httpGetEnabled="true" />          
  <serviceDebug includeExceptionDetailInFaults="false" />
  <serviceCredentials>
    <windowsAuthentication allowAnonymousLogons="false" includeWindowsGroups="true" />
  </serviceCredentials>
  <dataContractSerializer maxItemsInObjectGraph="2147483647" />
</behavior>

We can also do this in code. Example below is to set the MaxItemsInObjectGraph for a specific service operation.

var dataContractBehavior = operation.Behaviors.Find<DataContractSerializerOperationBehavior>();
if (dataContractBehavior != null)
    dataContractBehavior.MaxItemsInObjectGraph = 2147483647;

Related FAQs

We can add an IErrorHandler to a WCF service so that it takes care for exception handling for the said service. We can add it via the configuration file by using BehaviorExtensionElement and IServiceBehavior.
Change MaxItemsInObjectGraph for a WCF Service  (2098 Views)