Software & Development

.NET WCF The underlying connection was closed

Recently, I spent a few hours solving an issue with sample WCF (Windows Communication Foundation) where my connection from client was closed after the result was received. The error message was following:

The underlying connection was closed: The connection was closed unexpectedly.

There are plenty of blogs explaining how I have to change the client and server configuration (maxRequestLength, maxBufferSize and maxItemsInObjectGraph), e.g. herehere or here. However, in my case the problem was different. If the Service Contractor class defines an operation (method) O1 that returns class C1 (or class that contains property of this type) and O1 returns in fact C2 that derives from C1 you’ll get this error.

The solution as simple as using the KnownType annotation as mentioned in this article. Below the [DataContract] add [KnownType(typeof(C2))].