2010-07-14 86 views
5

是否有可能獲得WCF服務來向客戶端返回'錯誤'?我被認爲使用SOAP時這是可能的,但我想返回JSON。WCF服務返回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錯誤請求'響應,並顯示HTML格式的錯誤。 (當我includeExceptionDetailInFaults,我可以看到「理性......」和FaultException的細節,但對TestFault沒有詳細說明。)

的web服務,返回JSON OK了Exception(或FaultException)是不是被當拋出。

任何建議..?

+0

又一次嘗試在解決這一這裏http://iainjmitchell.com/blog/?p=142 – 2011-06-20 14:33:23

回答

7

編輯:固定鏈接+添加摘要。

你可以找到的解釋和解決方案here

總結從鏈路解決方案,延長WebHttpBehavior,爲了增加自己的實現IErrorHandler的覆蓋AddServerErrorHandlers。此實現將從服務調用中提取錯誤並生成錯誤信息。

鏈接的文章還顯示瞭如何編寫自己的Service Host Factory來設置此行爲。

+0

感謝Timores。我從此工作,但設置了一個'BehaviorExtensionElement',以便可以在配置文件中指定行爲。 – 2010-07-14 14:33:38

+0

只好投票了,因爲鏈接的解決方案不再存在。 – Andreas 2016-06-24 12:35:24

+1

@Andreas,你是對的。我修復了鏈接並總結了其內容。 – Timores 2016-06-24 14:34:37

12

所有您需要的都可以從.NET 4.開始,詳情請參閱here。例如:

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

這看起來可能有效,但不幸的是需要.NET 4,在這種情況下我不能使用它。 – 2010-07-14 14:32:09

1

您jQuery.ajax()調用的錯誤回調應該是這樣的:

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

在你的WCF服務,傳遞一個例外WebFaultException構造。您的自定義消息將通過responseObj.Message可以訪問上面的javascript:

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