如何在使用WCF客户端时以编程方式设置MaxReceivedMessageSize?

时间:2010-03-16 19:22:18

标签: wcf

我想以编程方式在我的客户端中将MaxReceivedMessageSize属性设置为某个更高的限制(由于(400)错误请求错误)。 这是我正在使用的代码...

WCFServiceTestClient wcfClient = 
    new WCFServiceTestClient(new wsHttpBinding(), strServiceURL);

我的服务网址是动态的,因此无法使用web.config。

//The following code doesn't seem to take effect
((WSHttpBinding)wcfClient.ChannelFactory.Endpoint.Binding)
        .MaxReceivedMessageSize = 2147483647;

我做错了什么?

3 个答案:

答案 0 :(得分:23)

您是否尝试重新排序调用,以便在实例化客户端之前设置MaxReceivedMessageSize?例如,

var binding = new wsHttpBinding();
binding.MaxReceivedMessageSize = Int32.MaxValue; 
var wcfClient = new WCFServiceTestClient(binding, strServiceURL); 

但这可能会或可能不会帮助您解决400错误。

答案 1 :(得分:9)

我的wcf服务中遇到了类似的问题,我用以下方法解决了这个问题:

CustomBinding binding = (CustomBinding)PDAServiceContractClient.CreateDefaultBinding();
            HttpTransportBindingElement httpBindingElement = new HttpTransportBindingElement();
            httpBindingElement.MaxBufferSize = Int32.MaxValue;
            httpBindingElement.MaxReceivedMessageSize = Int32.MaxValue;
            binding.Elements.Add(httpBindingElement);

            string address = PDAServiceContractClient.EndpointAddress.Uri.ToString();
            m_proxy = new PDAServiceContractClient(binding, new EndpointAddress(address));

答案 2 :(得分:0)

这很好用,虽然不是那么明显。它保留了所有现有的绑定属性,仅调整MaxReceivedMessageSize(顺便提一下,MaxBufferSize也增加到相同的大小。)

Dim oClient as WcfClient = New WcfClient
CType(oClient.Endpoint.Binding, ServiceModel.BasicHttpBinding).MaxReceivedMessageSize = Int32.MaxValue