WCF Client Catching SoapException from asmx webservice
本文关键字:asmx webservice from SoapException Client Catching WCF | 更新日期: 2023-09-27 18:33:02
我有一个调用asmx Web服务的WCF服务。 该 Web 服务抛出如下所示的 enception:
<soap:Body>
<soap:Fault>
<faultcode>soap:Server</faultcode>
<faultstring>System.Web.Services.Protocols.SoapException: error
service.method()</faultstring>
<faultactor>https://WEBADDRESS</faultactor>
<detail>
<message>Invalid ID</message>
<code>00</code>
</detail>
</soap:Fault>
</soap:Body>
在 c# 中,我可以将其捕获为 FaultException,但它没有 details 属性。 我如何获得此例外的详细信息?
在玩了很长时间之后,我发现从 FaultException 对象中可以创建一个 MessageFault。 MessageFault 有一个属性 HasDetail,用于指示 detail 对象是否存在。 从那里,您可以将 Detail 对象作为 XmlElement 获取并获取其值。以下捕获块运行良好。
catch (System.ServiceModel.FaultException FaultEx)
{
//Gets the Detail Element in the
string ErrorMessage;
System.ServiceModel.Channels.MessageFault mfault = FaultEx.CreateMessageFault();
if (mfault.HasDetail)
ErrorMessage = mfault.GetDetail<System.Xml.XmlElement>().InnerText;
}
这会从问题中的示例错误中生成"无效 ID"。
在
调用 Web 服务时使用 try catch 块,然后捕获 SOAP 异常
catch (SoapException e)
{
e.Detail
}
如果要抛出非基本的 FaultExceptions(即包含详细信息的异常),则需要将此行为添加到 web.config 中,并使用 behaviorConfiguration
属性将其附加到service
。
<serviceBehaviors>
<behavior name="YourServiceNameOrAnythingReallyServiceBehavior">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
然后,您需要抛出一个new FaultException<T>(T)
其中 T 是包含详细信息的对象的类型。然后,您可以在外面FaultException<T>
捕捉它,并以这种方式查看详细信息。T 可能是复杂类型,如果是,则必须使用[DataContractAttribute]
修饰该类型