tags:

views:

41

answers:

2

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..?

A: 

You can find an explanation and a solution here

Timores
Thanks Timores. I worked from this but setup a `BehaviorExtensionElement` so that the behaviour could be specified in the configuration file.
Joe Freeman
A: 

All what you need is possible. see http://blogs.msdn.com/b/endpoint/archive/2010/01/21/error-handling-in-wcf-webhttp-services-with-webfaultexception.aspx

Oleg
This looks like it might have worked, but unfortunaetly requires .NET 4, which I can't use in this case.
Joe Freeman