WCF and the CommunicationException


When working with Windows Communication Foundation (WCF) Services, you will no doubt encounter various System.ServiceModel exceptions. The one error I normally find very hard to debug and solve is the System.ServiceModel.CommunicationException (CommunicationException crossed a native/managed boundary). The error message associated with this exception is {“The underlying connection was closed: The connection was closed unexpectedly.”}.

The problem raises its ugly head after a service method has been added or updated, and appears to occur during serialization and deserialization. As the serialized object is being deserialized, the object being deserialized is not of a known type. This results in the above error message being thrown. The solution to this problem is to make sure that you are returning the correct type. There are attributes that you can set on your contract called KnownType and ServiceKnownType. But in my case, setting these attributes had no effect on solving this particular issue.

My solution was to create a separate method in the service passing back the correct type. This worked but created a secondary issue. The secondary issue was still a System.ServiceModel.CommunicationException (CommunicationException crossed a native/managed boundary). But this time the error message was “The maximum message size quota for incoming messages (65535) has been exceeded. To increase the quota, use the MaxReceivedMessageSize property on the appropriate binding element.”

To solve this secondary issue was very straight forward. In the WCF Test Client, I right clicked on the Client Config file and from the popup menu selected Edit with SvcConfigEditor. This opens the Service Configuration Editor application with the client config file used by the test client. I then navigated to Bindings and clicked on the binding for my service which happened to be using BasicHttpBinding because it had to work on a Windows Phone 7 Device. Under the general settings, I then proceeded to change both the MaxBufferSize and MaxReceivedMessageSize to the maximum value of 2147483647 which is 2 GB.

I then saved the config file and re-ran my WCF Test, and hey-presto, it worked.

So the moral of the story is this. If you get a CommunicationException, make sure that you are returning the correct type and that it is a known type, and within the client config files make sure that the MaxBufferSize and MaxReceivedMessageSize is appropriate for the server response.

Advertisements