C# WCF客户端从asmx webservice捕获SoapException

C# WCF客户端从asmx webservice捕获SoapException,c#,wcf,asmx,faultexception,soapfault,C#,Wcf,Asmx,Faultexception,Soapfault,我有一个调用ASMXWeb服务的WCF服务。该web服务引发的异常如下所示: <soap:Body> <soap:Fault> <faultcode>soap:Server</faultcode> <faultstring>System.Web.Services.Protocols.SoapException: error

我有一个调用ASMXWeb服务的WCF服务。该web服务引发的异常如下所示:

        <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属性。如何获取此异常的详细信息?

在调用web服务时使用try-catch块,然后捕获soap异常

catch (SoapException e)
{
    e.Detail
}
如果要抛出非基本故障异常,即包含详细信息的异常,则需要将此行为添加到web.config,并使用behaviorConfiguration属性将其附加到服务

  <serviceBehaviors>
    <behavior name="YourServiceNameOrAnythingReallyServiceBehavior">
      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="true" />
    </behavior>
  </serviceBehaviors>

然后,您需要抛出一个新的faultexception,其中T是包含详细信息的对象的类型。然后,您可以在外部将其捕获为FaultException,并以这种方式查看详细信息。T可能是一个复杂的类型,如果是这样的话,您必须用[DataContractAttribute]

来修饰该类型。在长时间使用它之后,我发现可以使用FaultException对象创建MessageFault。MessageFault具有属性HasDetail,该属性指示是否存在详细信息对象。从那里,您可以获取作为XmlElement的细节对象并获取其值。下面的catch块工作得很好

 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。从问题中的示例错误中。

在c中,我可以将其捕获为FaultException,但它没有details属性。您是在调用旧时间web服务,还是您的WCF正在调用另一个WCF?您是在WCF服务中捕获异常,还是在调用程序中捕获异常。问题在于我在调用asmx服务,我在WCF服务中捕获异常FaultException没有详细信息,只有FaultException,而且我认为旧的Web服务不会抛出FaultException,因此您的运气不佳,即使它们抛出了,需要对它们进行配置才能这样做。如果您没有访问Web服务的权限,那么您又是运气不佳。而是将其作为SoapException捕获,并使用它提供的详细信息。SoapExceptions详细信息没有任何用处。因此,您告诉我,asmx服务引发的异常不能被.Net中的客户端检查