在Web服务中捕获FaultException

时间:2009-12-16 04:34:32

标签: c# wcf sharepoint

我正在使用.net服务模型调用C#Web服务,有时此Web服务会抛出Microsoft.SharePoint.SoapServer.SoapServerException。我可以在客户端代码中将此异常作为FaultException捕获,但是我无法使用FaultException获取Web服务返回的友好错误消息。

以下是出现异常时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框架没有正确地反序列化上面的响应,或者我在这里使用了错误的excepetion类。

我可以从FaultException获得的唯一错误消息是“类型'Microsoft.SharePoint.SoapServer.SoapServerException'的异常被抛出”没有别的。

请注意,我对网络服务没有任何控制权。

2 个答案:

答案 0 :(得分:24)

花了一些时间在此之后我能够找到解决方案,您可以使用以下代码段访问异常消息,

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

谢谢大家的回复。

答案 1 :(得分:3)

Web服务不直接使用异常。相反,他们返回错误。 WSDL旨在描述可能的错误以及<detail/>元素的内容。您需要查看WSDL以确定返回给您的错误。

如果故障名为SharePointFault,则WCF会将其转换为名为FaultException<SharePointFault>的异常。此异常可能包含errorstringerrorcode的属性。您应该能够使用这些属性来检索故障消息中发送的值。

相关问题