Partilhar via


ServiceBehaviorAttribute.IncludeExceptionDetailInFaults Propriedade

Definição

Obtém ou define um valor que especifica que exceções gerais de execução sem tratamento devem ser convertidas em um FaultException<TDetail> tipo ExceptionDetail e enviadas como uma mensagem de falha. Defina isso true como somente durante o desenvolvimento para solucionar problemas de um serviço.

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

true se exceções sem tratamento devem ser retornadas como falhas SOAP; caso contrário, false. O padrão é false.

Exemplos

O exemplo de código a seguir demonstra as ServiceBehaviorAttribute propriedades. A BehaviorService classe usa o ServiceBehaviorAttribute atributo para indicar que:

  • Os métodos de implementação são invocados no thread da interface do usuário.

  • Há um objeto de serviço para cada sessão.

  • O serviço é de thread único e não dá suporte a chamadas reentradas.

Além disso, no nível da operação, os OperationBehaviorAttribute valores indicam que o TxWork método se insere automaticamente em transações fluídas ou cria uma nova transação para fazer o trabalho e que a transação é confirmada automaticamente se uma exceção sem tratamento não ocorrer.

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

A associação subjacente deve dar suporte a transações fluídas para que o exemplo de código a seguir seja executado corretamente. Para dar suporte a transações fluídas usando a WSHttpBindingpropriedade , por exemplo, defina a TransactionFlow propriedade true como no código ou em um arquivo de configuração de aplicativo. O exemplo de código a seguir mostra o arquivo de configuração do exemplo 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>

Comentários

Defina IncludeExceptionDetailInFaults para true habilitar informações de exceção para fluir para clientes para fins de depuração. Essa propriedade requer uma associação que dê suporte a mensagens solicitação-resposta ou duplex.

Em todos os aplicativos gerenciados, os erros de processamento são representados por Exception objetos. Em aplicativos baseados em SOAP, como aplicativos WCF, métodos que implementam operações de serviço comunicam informações de erro usando mensagens de falha SOAP. Como os aplicativos WCF são executados em ambos os tipos de sistemas de erro, todas as informações de exceção gerenciadas que precisam ser enviadas ao cliente devem ser convertidas de exceções em falhas SOAP. Para obter mais informações, consulte Especificando e tratando falhas em contratos e serviços.

Durante o desenvolvimento, talvez você queira que seu serviço também envie outras exceções de volta ao cliente para ajudá-lo na depuração. Esse é um recurso somente de desenvolvimento e não deve ser empregado em serviços implantados.

Para facilitar o desenvolvimento de depuração, defina como IncludeExceptionDetailInFaultstrue no código ou usando um arquivo de configuração de aplicativo.

Quando habilitado, o serviço retorna automaticamente informações de exceção mais seguras para o chamador. Essas falhas aparecem no cliente como FaultException<TDetail> objetos do tipo ExceptionDetail.

Importante

Configuração IncludeExceptionDetailInFaults para true permitir que os clientes obtenham informações sobre exceções internas do método de serviço; ela só é recomendada como uma forma de depurar temporariamente um aplicativo de serviço. Além disso, o WSDL para um método que retorna exceções gerenciadas não tratadas dessa forma não contém o contrato do FaultException<TDetail> tipo ExceptionDetail. Os clientes devem esperar a possibilidade de uma falha SOAP desconhecida obter as informações de depuração corretamente.

Definir essa propriedade para true também pode ser feita usando um arquivo de configuração de aplicativo e o <elemento serviceDebug> , como mostra o exemplo de código a seguir.

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

Aplica-se a