Problems returning a large amount of data through WCF

3

Good afternoon,

I have a web service done in WCF, when I make a query in the database and return a large amount of records it gives me the following error:

An unhandled exception of type 'System.ServiceModel.CommunicationException' occurred in mscorlib.dll Additional information: The maximum size of incoming messages (65536) has been exceeded. To increase the quota, use the MaxReceivedMessageSize property on the appropriate membership element.

Can anyone help me?

    
asked by anonymous 21.01.2016 / 18:20

1 answer

8

When you use the "Add Service Reference" to generate the client for the WCF service, this tool adds the information necessary for the client to communicate with the server in its configuration file (app.config or web.config). One of them is binding to be used.

You can change the binding setting to increase this quota that the error message is saying is being exceeded. For example:

<bindings>
  <basicHttpBinding>
    <binding
        name="BasicHttpBinding_MyService"
        maxReceivedMessageSize="1000000" />
  </basicHttpBinding>
</bindings>

Another alternative is to do this in code, before calling a client function for the first time, as in the example below.

        var c = new ServiceReference1.MyServiceClient();
        var binding = c.Endpoint.Binding;
        if (binding is BasicHttpBinding)
        {
            ((BasicHttpBinding)binding).MaxReceivedMessageSize = 1000000;
        }
        else if (binding is WSHttpBinding)
        {
            ((WSHttpBinding)binding).MaxReceivedMessageSize = 1000000;
        }
        else
        {
            // outros tipos
            var newBinding = new CustomBinding(binding);
            for (var i = 0; i < newBinding.Elements.Count; i++)
            {
                if (newBinding.Elements[i] is TransportBindingElement) {
                    ((TransportBindingElement)newBinding.Elements[i]).MaxReceivedMessageSize = 1000000;
                }
            }

            c.Endpoint.Binding = newBinding;
        }
    
21.01.2016 / 18:50