简体   繁体   中英

WCF service to return JSON-formatted faults

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

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.

The error callback of your jQuery.ajax() call should look like this:

error: function (xhr, status, error) {
  var responseObj = JSON.parse(xhr.responseText);
  alert('Request failed with error: "' + responseObj.Message);
}

In your WCF Service, pass an exception to the WebFaultException constructor. Your custom message will be accessible via responseObj.Message in the above javascript:

public class AJAXService : IAJAXService
{
  public void SomeMethod()
  {
    throw new WebFaultException<Exception>(new Exception("some custom error message!"), HttpStatusCode.InternalServerError);
  }
}   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM