2009-12-16 67 views
8

我正在使用.net服務模型調用C#Web服務,偶爾此Web服務會引發Microsoft.SharePoint.SoapServer.SoapServerException。我可以在客戶端代碼中將這個特殊異常捕獲爲FaultException,但是我無法使用FaultException獲取Web服務返回的友好錯誤消息。在WebServices中捕獲FaultException

以下是存在異常時Web服務的網絡跟蹤。

<?xml version="1.0" encoding="utf-8"?> 
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <soap:Body> 
     <soap:Fault> 
      <faultcode>soap:Server</faultcode> 
      <faultstring>Exception of type 'Microsoft.SharePoint.SoapServer.SoapServerException' was thrown.</faultstring> 
      <detail> 
       <errorstring xmlns="http://schemas.microsoft.com/sharepoint/soap/">Access to this Web site has been blocked. 
    Please contact the administrator to resolve this problem.</errorstring> 
       <errorcode xmlns="http://schemas.microsoft.com/sharepoint/soap/">0x81020071</errorcode> 
      </detail> 
     </soap:Fault> 
    </soap:Body> 
</soap:Envelope> 

我非常有興趣在上述響應中獲取errorstring節點之間的內容。但是,從FaultException類我無法檢索上述錯誤消息。這是否意味着.NET框架沒有正確反序列化上述響應,或者我在這裏使用錯誤的exceletion類。

我可以從FaultException中獲得的唯一錯誤消息是「異常類型'Microsoft.SharePoint.SoapServer.SoapServerException'被引發」沒有別的。

請注意,我對Web服務沒有任何控制權。

回答

24

花費更多的時間在這我能找到一個解決方案後,您可以使用下面的代碼段可以訪問異常消息,

FaultException faultException = (FaultException)exception; 
MessageFault msgFault = faultException.CreateMessageFault(); 
XmlElement elm = msgFault.GetDetail<XmlElement>(); 

謝謝大家的回覆。

+0

謝謝,你的代碼只是給了我和如何解決我的問題的想法(經過幾個小時的戰鬥)。如果您正在通過反射調用wcf代理類的方法,請注意該錯誤異常作爲內部函數的clr throw反射異常。 – 2012-03-26 13:10:00

2

Web服務不直接使用異常。相反,他們會返回錯誤。 WSDL旨在描述可能的錯誤,以及<detail/>元素的內容。您需要查看WSDL以確定將哪個錯誤返回給您。

如果錯誤名爲SharePointFault,那麼WCF會將其轉換爲名爲FaultException<SharePointFault>的異常。該例外可能具有errorstringerrorcode的屬性。您應該能夠使用這些屬性來檢索故障消息中發送的值。

+0

嗯......我沒有在Web服務的WSDL定義中看到這樣的描述。但是,如果我將上述Web服務用作普通Web引用(而不是服務引用),則可以將上述異常捕獲爲System.Web.Services.Protocols.SoapException,並且可以訪問OuterXml或InnerXml屬性中的錯誤消息的System.Web.Services.Protocols.SoapException對象。 – Shamika 2009-12-16 06:22:21

+0

如果沒有wsdl:fault元素,那麼您就不能使用http://msdn.microsoft.com/en-us/library/system.servicemodel.faultexception.createmessagefault.aspx。 – 2009-12-16 10:28:46

+0

是的,這是唯一的選擇 – Shamika 2009-12-17 04:06:51