سؤال

I have a WCF service that calls an asmx web service. That web service throws an enxception that looks like this:

        <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>

In c# I can catch it as a FaultException however it has no details property. How can I get at the details of this Exception?

هل كانت مفيدة؟

المحلول

After playing around with this for a long time I found that off of the FaultException object you can create a MessageFault. MessageFault has a property HasDetail that indicates if the detail object is present. From there you can grab the Detail object as an XmlElement and get its value. The following catch block works well.

 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;
  } 

This yields "Invalid ID." from the sample fault in the question.

نصائح أخرى

use a try catch block around the call to the web service, and then catch the soap exception

catch (SoapException e)
{
    e.Detail
}

if you want to throw non-basic FaultExceptions, (ie ones that contain details) you will need to add this behavior to your web.config and attach it to your service by using the behaviorConfiguration attribute.

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

Then you would want to throw a new FaultException<T>(T) where T is the type of the object that contains the details. You can then catch it on the outside as FaultException<T> and view the details that way. T may be a complex type, if so, you must decorate that type with the [DataContractAttribute]

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top