WCF FaultException<ApplicationException> fails if an inner exception is specified for the ApplicationException

StackOverflow https://stackoverflow.com/questions/22446096

  •  15-06-2023
  •  | 
  •  

Pregunta

I have been debugging an issue with my newly minted WCF services Fault contract and finally found out what was breaking it.

I defined the service like so:

[ServiceContract]

public interface IService1
{

    [OperationContract]
    [FaultContract(typeof(ApplicationException))]
    string GetData();
}

in my service I was handling exception in the service like so:

    public string GetData()
    {
        try
        {
           // do stuff
        }
        catch(Exception e)
        {
            ApplicationException ae = new ApplicationException("oh dear!", e );
            throw new FaultException<ApplicationException>( ae, 
                                                 new FaultReason(ae.Message));
        }
    }

However, the client would never receive the fault exception, instead it would get an exception which said:

An error occurred while receiving the HTTP response to ... This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server ( possibly due to the service shutting down).See server logs for more details

If I changed my code on the service like so (ie: do NOT set the inner exception when constructing the ApplicationException) it works as expected.

    public string GetData()
    {
        try
        {
           // do stuff
        }
        catch(Exception e)
        {
            ApplicationException ae = new ApplicationException("oh dear!");
            throw new FaultException<ApplicationException>( ae, 
                                                 new FaultReason(ae.Message));
        }
    }

Can anyone explain why this might fail if the inner exception is set? I could not see it anywhere in the documentation.

¿Fue útil?

Solución

When the ApplicationException is sent to the client via FaultException<T> without the InnerException, then it is sent only as a string. However, when the InnerException is set, then the ApplicationException itself is sent.

The Exception type is serializable in .NET (it is often incorrectly cited as not being serializable), however, frequently the contents of the Data property are not serializable. This will cause a serialization issue which is what I believe you are experiencing.

There are a few workarounds to this issue: You can set the Data property to null by using reflection or you can create your own class.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top