Search code examples
wcfwcf-binding

WCF faulted event not called on client side


I have a wcf service callback. the initialization of the service is done on the client side. every now and then the service is getting into faulted state. I tried registering the faulted event on both client and server. the problem is that only the server side faulted event is firing and the client doesn't know that something went wrong, and since the client creates the connection it doesn't help me the the server side knows about it. Is there something I can do on the server side faulted event to tell the client side that something went wrong?


Solution

  • As per your concern,The problem is that only the server side faulted event is firing and the client doesn't know.

    When an exception occurs in a WCF service, the service serializes the exception into a SOAP fault, and then sends the SOAP fault to the client.

    the client doesn't know that something went wrong

    By default unhandled exception details are not included in SOAP faults that are propagated to client applications for security reasons. Instead a generic SOAP fault is returned to the client.

    Is there something I can do on the server side faulted event to tell the client side that something went wrong? You can include/append the exception to the SOAP faults. Anywhere exception occurs in the code ,mark it as soap fault.

    For example you are trying to throw an exception like divide by zero,catch it and include it in FaultException.

    throw new FaultException("Denomintor cannot be ZERO", new FaultCode("DivideByZeroFault"));
    

    If you want to include exception details in SOAP faults, enable IncludeExceptionDetailInFaults setting.

    Through configuration

    <behaviors>
      <serviceBehaviors>
        <behavior name="inculdeExceptionDetails">
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    

    Through code if you need ,then

    [ServiceBehavior(IncludeExceptionDetailInFaults=true)]
    

    By this way the any exception occurs at server side is carried to client in the form of SOAP FAULT inside the envelope of SOAP message.And catch it at client side.

    catch (FaultException ex)
    {
    string errorMessage= = ex.Message;
    }
    

    Note:An unhandled exception in the WCF service, will cause the communication channel to fault and the session will be lost. Once the communication channel is in faulted state, we cannot use the same instance of the proxy class any more. We will have to create a new instance of the proxy class.