February 22, 2010

.NET 4.0 WCF: Issues with WebFaultException

         In WCF 3.5,  WebHttpBinding  doesn't return faults in expected response format. It ignores the format specified in the contract, and returns the error in html format. I was expecting error to be in the format specified in the WebGet/WebInvoke. For one of my project with WCF RESTful/JQuery solution stack, I end up writing a custom error handler implementing IErrorHandler to receive the fault in the desired JSON format.

         .NET 4.0 introduces a class WebFaultException<> to tackle this formatting issue. What all you have to do is throw the fault using this class, and you get the HTTP response in correct desired format. Digging deep the WebHttpErrorHandler with Reflector, I found that formatting decision is made based on type of the fault thrown.The expected fault should of type  IWebFaultException. WebFaultException implements IWebFaultException.

        I see few problems with this solution. If I forget to use WebFaultException in one of my operation implementation, I am screwed, I get response in same old html format. Deriving message format from the implementation(i.e. service behavior) seems to me odd.  Second one, If I have to go with this solution and to retire my custom error handler, I will have to modify code in several places changing use of FaultException to WebFaultException. These two issues making me to think whether I should stick with custom error handler solution unless situtation demands for different status codes. With WebFaultException, you can set http status code.   I was just throwing one status code BadRequest, and application specific status codes were in the fault details object.