Is it possible to get a WCF service to return a 'fault' to the client? I'm led to believe this is possible when using SOAP, but I'd like to be returning JSON.
Ideally, the HTTP response code would be set to something to indicate that an error occured, and then details of the problem would be available in the JSON response.
Currently, I'm doing something like this:
[ServiceContract]
public class MyService
{
[OperationContract]
[WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
[FaultContract(typeof(TestFault))]
public MyResult MyMethod()
{
throw new FaultException<TestFault>(new TestFault("Message..."), "Reason...");
}
}
Where TestFault
looks like this:
[DataContract]
public class TestFault
{
public TestFault(string message)
{
this.Message = message;
}
[DataMember]
public string Message { get; set; }
}
There's nothing particularly special in the service configuration at the moment.
This results in a '400 Bad Request' response, with an HTML-formatted error. (When I includeExceptionDetailInFaults
, I can see the 'Reason...' and details of the FaultException
, but no details on the TestFault
.)
The web service returns JSON ok when an Exception
(or FaultException
) isn't being thrown.
Any suggestions..?