草庐IT

c# - 抛出 FaultException 时 WCF 错误 "The size necessary to buffer the XML content exceeded the buffer quota"

coder 2024-05-20 原文

我试图在 WCF 应用程序的服务器端抛出 FaultException。我使用 DTO 作为此异常的有效负载。从某个时候(对于那种大对象)我开始在客户端收到“缓冲 XML 内容所需的大小超出了缓冲区配额”异常。所有绑定(bind)消息大小参数和 maxDepth 都设置为最大的值以排除怀疑。 有人遇到过这个问题吗?网上好像还没有解决办法。 设置

<dataContractSerializer maxItemsInObjectGraph="2147483647" ignoreExtensionDataObject="true" />

没有帮助。

最佳答案

问题出在 ClientRuntime 的“MaxFaultSize”参数中,默认值为 65535,因此默认情况下您无法在 WCF 的错误中传递大负载。要更改此值,您应该像这样编写自定义 EndpointBehavior:

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;
    }
}

并在创建代理时将其应用于客户端代码中的端点:

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

或者,在没有代理的情况下,只转换客户端来添加行为:

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

之后一切都会好起来的。 我花了很多时间寻找答案,希望这对某人有所帮助。

关于c# - 抛出 FaultException 时 WCF 错误 "The size necessary to buffer the XML content exceeded the buffer quota",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21259954/

有关c# - 抛出 FaultException 时 WCF 错误 "The size necessary to buffer the XML content exceeded the buffer quota"的更多相关文章

随机推荐