ServiceBehaviorAttribute.IncludeExceptionDetailInFaults Propiedad

Definición

Obtiene o establece un valor que especifica que las excepciones de ejecución generales no controladas se convertirán en una FaultException<TDetail> de tipo ExceptionDetail, y se enviarán como mensaje de error. Establezca este valor como true sólo durante el desarrollo para solucionar problemas de un servicio.

public:
 property bool IncludeExceptionDetailInFaults { bool get(); void set(bool value); };
public bool IncludeExceptionDetailInFaults { get; set; }
member this.IncludeExceptionDetailInFaults : bool with get, set
Public Property IncludeExceptionDetailInFaults As Boolean

Valor de propiedad

true si las excepciones no controladas se devuelven como errores de SOAP; de lo contrario, false. De manera predeterminada, es false.

Ejemplos

En el ejemplo de código siguiente se muestran las propiedades ServiceBehaviorAttribute. La clase BehaviorService utiliza el atributo ServiceBehaviorAttribute para indicar que:

  • Los métodos de implementación se invocan en el subproceso de la interfaz de usuario.

  • Hay un objeto de servicio para cada sesión.

  • La instancia del servicio es de subproceso único y no admite llamadas reentrantes.

Además, en el nivel de la operación, los valores OperationBehaviorAttribute indican que el método TxWork da de alta automáticamente las transacciones de flujo o crea una transacción nueva para hacer el trabajo y que se confirma la transacción automáticamente si no se produce una excepción no controlada.

using System;
using System.ServiceModel;
using System.Transactions;

namespace Microsoft.WCF.Documentation
{
  [ServiceContract(
    Namespace="http://microsoft.wcf.documentation",
    SessionMode=SessionMode.Required
  )]
  public interface IBehaviorService
  {
    [OperationContract]
    string TxWork(string message);
  }

  // Note: To use the TransactionIsolationLevel property, you
  // must add a reference to the System.Transactions.dll assembly.
  /* The following service implementation:
   *   -- Processes messages on one thread at a time
   *   -- Creates one service object per session
   *   -- Releases the service object when the transaction commits
   */
  [ServiceBehavior(
    ConcurrencyMode=ConcurrencyMode.Single,
    InstanceContextMode=InstanceContextMode.PerSession,
    ReleaseServiceInstanceOnTransactionComplete=true
  )]
  public class BehaviorService : IBehaviorService, IDisposable
  {
    Guid myID;

    public BehaviorService()
    {
      myID = Guid.NewGuid();
      Console.WriteLine(
        "Object "
        + myID.ToString()
        + " created.");
    }

    /*
     * The following operation-level behaviors are specified:
     *   -- The executing transaction is committed when
     *        the operation completes without an
     *        unhandled exception
     *   -- Always executes under a flowed transaction.
     */
    [OperationBehavior(
      TransactionAutoComplete = true,
      TransactionScopeRequired = true
    )]
    [TransactionFlow(TransactionFlowOption.Mandatory)]
    public string TxWork(string message)
    {
      // Do some transactable work.
      Console.WriteLine("TxWork called with: " + message);
      // Display transaction information.

      TransactionInformation info = Transaction.Current.TransactionInformation;
      Console.WriteLine("The distributed tx ID: {0}.", info.DistributedIdentifier);
      Console.WriteLine("The tx status: {0}.", info.Status);
      return String.Format("Hello. This was object {0}.",myID.ToString()) ;
    }

    public void Dispose()
    {
      Console.WriteLine(
        "Service "
        + myID.ToString()
        + " is being recycled."
      );
    }
  }
}
Imports System.ServiceModel
Imports System.Transactions

Namespace Microsoft.WCF.Documentation
  <ServiceContract(Namespace:="http://microsoft.wcf.documentation", SessionMode:=SessionMode.Required)> _
  Public Interface IBehaviorService
    <OperationContract> _
    Function TxWork(ByVal message As String) As String
  End Interface

  ' Note: To use the TransactionIsolationLevel property, you 
  ' must add a reference to the System.Transactions.dll assembly.
'   The following service implementation:
'   *   -- Processes messages on one thread at a time
'   *   -- Creates one service object per session
'   *   -- Releases the service object when the transaction commits
'   
    <ServiceBehavior(ConcurrencyMode:=ConcurrencyMode.Single, InstanceContextMode:=InstanceContextMode.PerSession, _
                     ReleaseServiceInstanceOnTransactionComplete:=True)> _
    Public Class BehaviorService
        Implements IBehaviorService, IDisposable
        Private myID As Guid

        Public Sub New()
            myID = Guid.NewGuid()
            Console.WriteLine("Object " & myID.ToString() & " created.")
        End Sub

        '    
        '     * The following operation-level behaviors are specified:
        '     *   -- The executing transaction is committed when
        '     *        the operation completes without an 
        '     *        unhandled exception
        '     *   -- Always executes under a flowed transaction.
        '     
        <OperationBehavior(TransactionAutoComplete:=True, TransactionScopeRequired:=True), TransactionFlow(TransactionFlowOption.Mandatory)> _
        Public Function TxWork(ByVal message As String) As String Implements IBehaviorService.TxWork
            ' Do some transactable work.
            Console.WriteLine("TxWork called with: " & message)
            ' Display transaction information.

            Dim info As TransactionInformation = Transaction.Current.TransactionInformation
            Console.WriteLine("The distributed tx ID: {0}.", info.DistributedIdentifier)
            Console.WriteLine("The tx status: {0}.", info.Status)
            Return String.Format("Hello. This was object {0}.", myID.ToString())
        End Function

        Public Sub Dispose() Implements IDisposable.Dispose
            Console.WriteLine("Service " & myID.ToString() & " is being recycled.")
        End Sub
    End Class
End Namespace

El enlace subyacente debe admitir transacciones de flujo para que el ejemplo de código siguiente se ejecute correctamente. Para admitir transacciones de flujo con WSHttpBinding, por ejemplo, establezca la propiedad TransactionFlow como true en el código o en un archivo de configuración de la aplicación. El ejemplo de código siguiente muestra el archivo de configuración para el ejemplo anterior:

<configuration>
  <system.serviceModel>
    <services>
      <service  
        name="Microsoft.WCF.Documentation.BehaviorService" 
        behaviorConfiguration="metadataAndDebugEnabled"
      >
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8080/SampleService"/>
          </baseAddresses>
        </host>
        <!--
          Note:
            This example code uses the WSHttpBinding to support transactions using the 
            WS-AtomicTransactions (WS-AT) protocol. WSHttpBinding is configured to use the  
            protocol, but the protocol is not enabled on some computers. Use the xws_reg -wsat+ 
            command to enable the WS-AtomicTransactions protocol in the MSDTC service.          
          -->
        <endpoint 
           contract="Microsoft.WCF.Documentation.IBehaviorService"
           binding="wsHttpBinding"
           bindingConfiguration="wsHttpBindingWithTXFlow"
           address="http://localhost:8080/BehaviorService"
          />
        <endpoint 
           contract="Microsoft.WCF.Documentation.IBehaviorService"
           binding="netTcpBinding"
           bindingConfiguration="netTcpBindingWithTXFlow"
           address="net.tcp://localhost:8081/BehaviorService"
          />
        <endpoint
          address="mex"
          binding="mexHttpBinding"
          contract="IMetadataExchange"
        />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="metadataAndDebugEnabled">
          <serviceDebug
            includeExceptionDetailInFaults="true"
          />
          <serviceMetadata
            httpGetEnabled="true"
            httpGetUrl=""
          />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <!-- binding configuration - configures a WSHttpBinding to require transaction flow -->
    <bindings>
      <wsHttpBinding>
        <binding name="wsHttpBindingWithTXFlow" transactionFlow="true" />
      </wsHttpBinding>
      <netTcpBinding>
        <binding name="netTcpBindingWithTXFlow" transactionFlow="true" />
      </netTcpBinding>
    </bindings>
  </system.serviceModel>
</configuration>

Comentarios

Establezca IncludeExceptionDetailInFaults como true para permitir que la información de excepción fluya a los clientes para fines de depuración. Esta propiedad requiere un enlace que admita tanto mensajería de solicitud-respuesta como dúplex.

En todas las aplicaciones administradas, los errores de procesamiento están representados mediante objetos Exception. En aplicaciones basadas en SOAP, como aplicaciones WCF, métodos que implementan operaciones de servicio comunican información de error mediante mensajes de error SOAP. Dado que las aplicaciones WCF se ejecutan en ambos tipos de sistemas de error, cualquier información de excepción administrada que deba enviarse al cliente debe convertirse de excepciones en errores soap. Para más información, consulte Especificación y administración de errores en contratos y servicios.

Durante el desarrollo puede desear que su servicio devuelva también otras excepciones al cliente para ayudarle a depurar. Esto es una característica sólo del desarrollo y no debería emplearse en servicios implementados.

Para facilitar el desarrollo de depuración, establezca en IncludeExceptionDetailInFaultstrue en código o mediante un archivo de configuración de aplicación.

Cuando se habilita, el servicio devuelve automáticamente información de excepción más segura al autor de la llamada. Estos errores aparecen en el cliente como objetos FaultException<TDetail> del tipo ExceptionDetail.

Importante

Establecer IncludeExceptionDetailInFaults en true permite a los clientes obtener información sobre las excepciones del método de servicio interno; solo se recomienda como una manera de depurar temporalmente una aplicación de servicio. Además, el WSDL de un método que devuelve excepciones administradas no controladas de esta manera no contiene el contrato para la FaultException<TDetail> de tipo ExceptionDetail. Los clientes deben esperar la posibilidad de que se produzca un error de SOAP desconocido para obtener correctamente la información de depuración.

Establecer esta propiedad true en también se puede realizar mediante un archivo de configuración de aplicación y el <elemento serviceDebug> , como se muestra en el ejemplo de código siguiente.

<serviceBehaviors>
  <behavior name="metadataAndDebugEnabled">
    <serviceDebug
      includeExceptionDetailInFaults="true"
    />
    <serviceMetadata
      httpGetEnabled="true"
      httpGetUrl=""
    />
  </behavior>
</serviceBehaviors>

Se aplica a