2011-03-02 224 views
5

我創建了一個帶有服務操作的WCF數據服務。WCF數據服務錯誤處理

我想生成一種業務異常。我嘗試生成WebFaultException,但是當服務操作引發此錯誤時,我不知道如何在客戶端捕獲此錯誤。

這裏是我的服務操作來模擬一個例外:

[WebGet] 
public void GenerateException() 
{ 
    throw new DataServiceException(403, "Custom Message"); 
} 

這裏是我的客戶:

WebClient wc = new WebClient(); 
wc.DownloadString(
    new Uri(
     "http://localhost:27820/WcfDataService1.svc/GenerateException" 
    ) 
); 

DownloadString是拋出一個異常,但它只是Internal Server Error,我看不到我的Custom Message

任何想法?

很多謝謝。

+0

嗨,你有沒有找到解決問題了嗎?我處於完全相同的情況,我什麼都沒有:/ – Mathieu 2012-04-11 17:54:06

回答

3

最好扔一個DataServiceException。 WCF數據服務運行時知道如何將屬性映射到HTTP響應,並始終將其包裝在TargetInvocationException中。

然後,您可以通過重寫HandleException在你的DataService像這樣解開這個客戶端消費者:

/// <summary> 
    /// Unpack exceptions to the consumer 
    /// </summary> 
    /// <param name="args"></param> 
    protected override void HandleException(HandleExceptionArgs args) 
    { 
     if ((args.Exception is TargetInvocationException) && args.Exception.InnerException != null) 
     { 
      if (args.Exception.InnerException is DataServiceException) 
       args.Exception = args.Exception.InnerException as DataServiceException; 
      else 
       args.Exception = new DataServiceException(400, args.Exception.InnerException.Message); 
     } 
    } 
3

您可以使用WCF FaultContract屬性拋出和處理businzess例外。

參考LinkExample

+0

感謝您發現此問題,然後發佈您的結果。這非常有幫助。 – 2011-11-28 05:12:12

0

我使用set EntitySetAccessRule到ALLREAD解決了我的403錯誤:

  config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);