ServiceBehaviorAttribute.IncludeExceptionDetailInFaults Свойство

Определение

Возвращает или задает значение, указывающее, что общие необработанные исключения выполнения должны быть преобразованы в тип FaultException<TDetail> и отправлены в ExceptionDetail виде сообщения об ошибке. Установите это значение true только во время разработки, чтобы устранить неполадки со службой.

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

Значение свойства

true Если необработанные исключения должны быть возвращены как ошибки SOAP; falseв противном случае . Значение по умолчанию — false.

Примеры

В следующем примере кода показаны ServiceBehaviorAttribute свойства. Класс BehaviorService использует ServiceBehaviorAttribute атрибут, чтобы указать, что:

  • Методы реализации вызываются в потоке пользовательского интерфейса.

  • Для каждого сеанса существует один объект службы.

  • Служба является однопоточной и не поддерживает повторные вызовы.

Кроме того, OperationBehaviorAttribute на уровне операции значения указывают, что TxWork метод автоматически заверяет в потоковые транзакции или создает новую транзакцию для выполнения работы, и что транзакция фиксируется автоматически, если необработанное исключение не возникает.

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

Базовая привязка должна поддерживать потоки транзакций для правильного выполнения следующего примера кода. Для поддержки потоковой транзакции, WSHttpBindingнапример, задайте TransactionFlow свойство true в коде или в файле конфигурации приложения. В следующем примере кода показан файл конфигурации для предыдущего примера.

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

Комментарии

Установите флажок IncludeExceptionDetailInFaults , чтобы true включить поток сведений об исключении клиентам в целях отладки. Для этого свойства требуется привязка, которая поддерживает обмен сообщениями с запросами или дуплексным обменом сообщениями.

Во всех управляемых приложениях ошибки обработки представлены объектами Exception . В приложениях на основе SOAP, таких как приложения WCF, методы, реализующие операции службы, передают сведения об ошибках с помощью сообщений об ошибках SOAP. Так как приложения WCF выполняются в обоих типах систем ошибок, все сведения об управляемых исключениях, которые необходимо отправить клиенту, необходимо преобразовать из исключений в ошибки SOAP. Дополнительные сведения см. в разделе "Указание и обработка ошибок" в контрактах и службах.

Во время разработки может потребоваться, чтобы служба также отправляла другие исключения клиенту, чтобы помочь вам в отладке. Это функция только для разработки и не должна использоваться в развернутых службах.

Чтобы упростить отладку разработки, задайте IncludeExceptionDetailInFaults значение true в коде или с помощью файла конфигурации приложения.

При включении служба автоматически возвращает для вызывающего абонента более безопасные сведения об исключении. Эти ошибки отображаются клиентом как FaultException<TDetail> объекты типа ExceptionDetail.

Important

Параметр IncludeExceptionDetailInFaults , позволяющий true клиентам получать сведения об исключениях внутренних методов службы; рекомендуется только в качестве способа временной отладки приложения-службы. Кроме того, WSDL для метода, возвращающего необработанные управляемые исключения таким образом, не содержит контракт для FaultException<TDetail> типа ExceptionDetail. Клиенты должны ожидать возможности неизвестного сбоя SOAP для правильного получения сведений об отладке.

Задание этого свойства true также можно сделать с помощью файла конфигурации приложения и <элемента serviceDebug> , как показано в следующем примере кода.

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

Применяется к