2011-08-12 72 views
23

我有一個測試Web服務的診斷工具。獲取WebClient錯誤作爲字符串

我希望該工具在出現問題時進行報告,因此我已經部署了一個服務來解決合同問題以對其進行測試。

當我瀏覽到它,我得到一個網頁一個非常描述性信息,例如:

An ExceptionDetail, likely created by IncludeExceptionDetailInFaults=true, whose value is: System.InvalidOperationException: An exception was thrown in a call to a WSDL export extension:
System.ServiceModel.Description.DataContractSerializerOperationBehavior contract: DataContract for type XXX cannot be added to DataContractSet since type XXX with the same data contract name XXX in namespace XXX is already present and the contracts are not equivalent etc..

我要的是能夠調用:

myErrorMsg = WebClient.DownloadString("MyBadService.svc"); 

,並得到這個有用的錯誤消息作爲字符串,但我得到以下WebException:

The remote server returned an error: (500) Internal Server Error.

我怎樣才能得到相同的錯誤一團糟我在瀏覽器中收到的年齡以字符串的形式返回,沒有發生異常?

謝謝。

+0

500錯誤意味着您的網站意外終止。 – Zenwalker

回答

54

你必須捕捉異常並閱讀迴應。

catch (WebException exception) 
{ 
    string responseText; 

    var responseStream = exception.Response?.GetResponseStream(); 

    if (responseStream != null) 
    { 
     using (var reader = new StreamReader(responseStream)) 
     { 
     responseText = reader.ReadToEnd(); 
     } 
    } 
} 
+1

嘿真棒謝謝 – lockstock

+4

如果由於連接錯誤,名稱解析失敗等引發WebException,這將炸燬。檢查以確保在嘗試從它獲取流之前有repsonse。 – JamieSee

+0

哈哈!終於找到了解決辦法。非常感謝@ccellar – Anand