WCF error "The size necessary to buffer the XML content exceeded the buffer quota" when throwing FaultException

The problem was in "MaxFaultSize" parameter in ClientRuntime, default value is 65535, so you can't pass large payload in WCF's faults by default. To change this value, you should write custom EndpointBehavior like this:

public class MaxFaultSizeBehavior : IEndpointBehavior
{
    private readonly int _size;

    public MaxFaultSizeBehavior(int size)
    {
        _size = size;
    }


    public void Validate(ServiceEndpoint endpoint)
    {            
    }

    public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
    {         
    }

    public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
    {            
    }

    public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
    {
        clientRuntime.MaxFaultSize = _size;
    }
}

and apply it to endpoint in client code when creating proxy:

_clientProxy.Endpoint.Behaviors.Add(new MaxFaultSizeBehavior(1024000));

or, without proxy, just cast the client to add the behavior:

_client = new MyServiceClient();
((ClientBase<IMyService>) _client).Endpoint.Behaviors.Add(new MaxFaultSizeBehavior(1024000));

After that everything will be fine. I've spent a lot of time searching answer, hope this helps somebody.

Tags:

C#

Wcf