Troubleshoot WCF The underlying connection was closed A connection that was expected to be kept alive was closed by the server

I’ve already blogged in the past on how to easily troubleshoot WCF Exception and that suggestion is valid for every exception you encounter in WCF. Today I have a function that gave the error

System.ServiceModel.CommunicationException: The underlying connection was closed: A connection that was expected to be kept alive was closed by the server. —> System.Net.WebException: The underlying connection was closed: A connection that was expected to be kept alive was closed by the server. —> System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. —> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host

This problem is usually caused by some error in the communication channel, but even in such a situation, enabling the trace listener immediately gave to you an idea of the problem.

SNAGHTML20daa9b

Figure 1: How to identify the problem thanks to WCF Trace Listener

In my situation the error is ClientProxy …. is not expected and this is due to the fact that I’m returning from WCF a couple of classes that are mapped with NHIbernate, the entity returned has a property of type Customer that is a lazy property, thus at runtime it is represented by a dynamic proxy that is not known to WCF. The solution is trivial, just issue a Fetch(obj => obj.Client) in the LINQ query to fetch Client and avoiding NH to create a proxy, but the key point is that with WCF trace listener, finding problems in WCF is matter of few seconds.

Gian MAria.