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..?
Change the return type of your GetResults to be List<Person> . Eliminate the code that you use to serialize the List to a json string - WCF does this for you automatically. WebInvoke with Method= "GET" is the same as WebGet, but since some of my methods are POST, I use all WebInvoke for consistency.
WCF has option to send the response in JSON object. This can be configured with WebGet or WebInvoke attribute. In this sample we can create the sample RESTful service to expose the method to read/add/update/delete the employee information.
WCF supports serializing data in JSON format.
All what you need is possible starting with .NET 4. see here for details. For example:
throw new WebFaultException<string>(
"My error description.", HttpStatusCode.BadRequest);
Edit: fixed link + added summary.
You can find an explanation and a solution here
To summarize the solution from the link, extend WebHttpBehavior and override AddServerErrorHandlers in order to add your own implementation of IErrorHandler. This implementation will extract the error from the service call and generate fault information.
The linked article also shows how to write your own Service Host Factory that sets up this behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With