How can I get WCF FaultException when server retur

2019-04-15 01:24发布

问题:

I have a WCF based test harness client for a set of web services. The test client allows me to see raw requests and responses going to and from the services. A Message Inspector endpoint behavior is used to "pick off" the raw requests and response messages and save them for later display in the UI.

This works great, except for the use case where invalid credentials are passed. The server returns an HTTP 401 along with a SOAP fault containing details of what happened. This hurts me in a couple ways:

  1. On the client this shows up as a MessageSecurityException not a FaultException, so I can't get the details from the fault.
  2. This exception appears to prevent the AfterReceiveReply event handler on my message inspector from firing, so I have no access to the raw response.

Is there any way I can handle this case so that the SOAP fault comes through as a FaultException and allow my message inspector to handle responses regardless of the HTTP status code that is returned?

Thanks!

回答1:

You cannot. You will only get a FaultException if a .NET exception occured in the server side code and has been caught.

HTTP 401 is "Access in unauthorized" - you'll get that exception before you even reach the server code --> this will always be a MessageSecurityException - never a FaultException (and there's no way to magically turn that into a FaultException, either).

Any exception that occurs before the execution even reaches the server code (things like EndpointNotFoundException or TimeoutException) are never fault exceptions.

All the WCF specific exceptions descend from a common base class, however - CommunicationException. So maybe you can handle that as a fallback.