将大数据发送到WCF - (413)请求实体

时间:2017-02-13 11:28:40

标签: c# winforms wcf

我有一个WCF服务器,

当我连接客户端(WinForm)时,我通过代码使用以下代码设置绑定参数:

String HTTP_SERVER = http:\\.......

private static BasicHttpBinding getBinding()
{
    //WSHttpBinding binding = new WSHttpBinding();
    BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.None);

    binding.TextEncoding = System.Text.Encoding.UTF8;
    binding.ReaderQuotas.MaxArrayLength = int.MaxValue;

    binding.ReceiveTimeout =new TimeSpan(8, 0,0);
    binding.SendTimeout = new TimeSpan(8, 0, 0);

    binding.MaxReceivedMessageSize = int.MaxValue;
    binding.MaxBufferSize = int.MaxValue;
    binding.MaxBufferPoolSize = int.MaxValue;


    binding.ReaderQuotas.MaxDepth = 64;
    binding.ReaderQuotas.MaxArrayLength= int.MaxValue;
    binding.ReaderQuotas.MaxStringContentLength = int.MaxValue;

    return binding;

}

ConnectionToServer = new ConnectionToServer (getBinding(), new EndpointAddress(HTTP_SERVER));

此代码运行正常,但现在我需要在Array中发送一个非常大的数据,当我尝试发送一个大数组时,我有这个错误:

(413)请求实体

我需要通过代码配置此连接,而不是通过xml配置。

我有一个例子来解决这个问题只能通过xml但我需要通过c#代码设置

是否需要在web.config(WCF服务器端)中设置任何参数?

1 个答案:

答案 0 :(得分:1)

如果这是在客户端上,您可以将以下行为添加到您的channelFactory:

public class MaxItemsInGraphBehavior : IEndpointBehavior
{
    public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
    {
    }

    public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
    {
        foreach (OperationDescription operation in endpoint.Contract.Operations)
        {
            var dc = operation.Behaviors.Find<DataContractSerializerOperationBehavior>();
            if (dc != null)
            {
                dc.MaxItemsInObjectGraph = int.MaxValue;
            }
        }
    }

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

    public void Validate(ServiceEndpoint endpoint)
    {
    }
}