WCF服务返回JSON格式的错误

时间:2010-07-14 11:16:19

标签: c# wcf json

是否有可能获得WCF服务以向客户端返回“错误”?在使用SOAP时我会相信这是可能的,但我想返回JSON。

理想情况下,HTTP响应代码将被设置为表示发生错误的内容,然后在JSON响应中提供问题的详细信息。

目前,我正在做这样的事情:

[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...");
    }
}

TestFault看起来像这样:

[DataContract]
public class TestFault
{
    public TestFault(string message)
    {
        this.Message = message;
    }

    [DataMember]
    public string Message { get; set; }
}

目前服务配置没有什么特别之处。

这会导致“400 Bad Request”响应,并出现HTML格式的错误。 (当我includeExceptionDetailInFaults时,我可以看到“原因...”和FaultException的详细信息,但TestFault没有详细信息。)

当没有抛出Exception(或FaultException)时,Web服务返回JSON ok。

有什么建议吗??

3 个答案:

答案 0 :(得分:13)

从.NET 4开始,您可能需要的所有内容。有关详细信息,请参阅here。例如:

throw new WebFaultException<string>(
    "My error description.", HttpStatusCode.BadRequest); 

答案 1 :(得分:7)

修改:固定链接+添加摘要。

您可以找到解释和解决方案here

要总结链接中的解决方案,请扩展WebHttpBehavior并覆盖AddServerErrorHandlers,以便添加自己的IErrorHandler实现。此实现将从服务调用中提取错误并生成错误信息。

链接文章还介绍了如何编写自己的服务主机工厂来设置此行为。

答案 2 :(得分:1)

jQuery.ajax()调用的错误回调应如下所示:

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

在WCF服务中,将异常传递给WebFaultException构造函数。您可以通过上面的javascript:

中的responseObj.Message访问您的自定义消息
public class AJAXService : IAJAXService
{
  public void SomeMethod()
  {
    throw new WebFaultException<Exception>(new Exception("some custom error message!"), HttpStatusCode.InternalServerError);
  }
}