在WebServices中捕获FaultException

Sha*_*ika 8 c# sharepoint wcf

我正在使用.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>
Run Code Online (Sandbox Code Playgroud)

我对在上面的响应中获取errorstring节点之间的内容非常感兴趣.但是,从FaultException类我无法检索上面的错误消息.这是否意味着.NET框架没有正确地反序列化上面的响应,或者我在这里使用了错误的excepetion类.

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

请注意,我对Web服务没有任何控制权.

Sha*_*ika 24

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

FaultException faultException = (FaultException)exception;
MessageFault msgFault = faultException.CreateMessageFault();
XmlElement elm = msgFault.GetDetail<XmlElement>();
Run Code Online (Sandbox Code Playgroud)

谢谢大家的回复.