Friday, June 11, 2010

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

There can be several reasons as to why we get the exception "WCF Client The underlying connection was closed: The connection was closed unexpectedly." on a WCF client. However i hit an interesting reason today.
So here's how my code structure was

[OperationContract]
Response ProcessRequest(Request request)

[DataContract]
enum SomeEnum
{
    [EnumMember]
    Value1 =1,
   
   [EnumMember]}
      Value2 =2,
}

[DataContract]
class Response
{
    [DataMember]
    string Message;
    [DataMember]
    SomeEnum EnumValue;
}

Now in my implementation i was trying to send a Response object which looked like
Response response = new Response(){Message="Some Message"};
return response;

Now this compiled fine and looked like it would work great however when i called the method ProcessRequest from my WCF client i got an exception message with the text "WCF Client The underlying connection was closed: The connection was closed unexpectedly.". There's no visible and obvious reason as to why this must be happening.
On enabling the WCF tracing i found that the error is in serializing the value of SomeEnum in this response. Apparently the Enum has nothing with value 0 and hence the framework is not able serialize the Response.
Apparently WCF server stack eats up this exception and closes the connection to the client. The exception doesn't even show up on visual studio and hence it is almost impossible to detect what's going on unless we have a server side tracing enabled.