IServiceBehavior 介面

定義

提供機制以在整個服務上修改或插入自訂延伸,包括 ServiceHostBase

public interface class IServiceBehavior
public interface IServiceBehavior
type IServiceBehavior = interface
Public Interface IServiceBehavior
衍生

範例

下列程式碼範例將示範如何使用組態檔中指定的服務行為,將自訂錯誤處理常式插入服務應用程式中。 在此範例中,錯誤處理常式會攔截所有例外狀況,並將其轉換為接著會傳回至用戶端的自訂 GreetingFault SOAP 錯誤。

下列 IServiceBehavior 實作不會新增任何繫結參數物件、會將自訂 System.ServiceModel.Dispatcher.IErrorHandler 物件新增至每個 ChannelDispatcher.ErrorHandlers 屬性中,然後驗證要套用服務行為且 System.ServiceModel.FaultContractAttribute 的型別為 GreetingFault 的每個服務作業。

// This behavior modifies no binding parameters.
#region IServiceBehavior Members
public void AddBindingParameters(
  ServiceDescription description,
  ServiceHostBase serviceHostBase,
  System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints,
  System.ServiceModel.Channels.BindingParameterCollection parameters
)
{
  return;
}

// This behavior is an IErrorHandler implementation and
// must be applied to each ChannelDispatcher.
public void ApplyDispatchBehavior(ServiceDescription description, ServiceHostBase serviceHostBase)
{
  Console.WriteLine("The EnforceGreetingFaultBehavior has been applied.");
  foreach(ChannelDispatcher chanDisp in serviceHostBase.ChannelDispatchers)
  {
    chanDisp.ErrorHandlers.Add(this);
  }
}

// This behavior requires that the contract have a SOAP fault with a detail type of GreetingFault.
public void Validate(ServiceDescription description, ServiceHostBase serviceHostBase)
{
  Console.WriteLine("Validate is called.");
  foreach (ServiceEndpoint se in description.Endpoints)
  {
    // Must not examine any metadata endpoint.
    if (se.Contract.Name.Equals("IMetadataExchange")
      && se.Contract.Namespace.Equals("http://schemas.microsoft.com/2006/04/mex"))
      continue;
    foreach (OperationDescription opDesc in se.Contract.Operations)
    {
      if (opDesc.Faults.Count == 0)
        throw new InvalidOperationException(String.Format(
          "EnforceGreetingFaultBehavior requires a "
          + "FaultContractAttribute(typeof(GreetingFault)) in each operation contract.  "
          + "The \"{0}\" operation contains no FaultContractAttribute.",
          opDesc.Name)
        );
      bool gfExists = false;
      foreach (FaultDescription fault in opDesc.Faults)
      {
        if (fault.DetailType.Equals(typeof(GreetingFault)))
        {
          gfExists = true;
          continue;
        }
      }
      if (gfExists == false)
      {
        throw new InvalidOperationException(
"EnforceGreetingFaultBehavior requires a FaultContractAttribute(typeof(GreetingFault)) in an operation contract."
        );
      }
    }
  }
}
#endregion
' This behavior modifies no binding parameters.
#Region "IServiceBehavior Members"
Public Sub AddBindingParameters(ByVal description As ServiceDescription, ByVal serviceHostBase As ServiceHostBase, ByVal endpoints As System.Collections.ObjectModel.Collection(Of ServiceEndpoint), ByVal parameters As System.ServiceModel.Channels.BindingParameterCollection) Implements IServiceBehavior.AddBindingParameters
  Return
End Sub

' This behavior is an IErrorHandler implementation and 
' must be applied to each ChannelDispatcher.
Public Sub ApplyDispatchBehavior(ByVal description As ServiceDescription, ByVal serviceHostBase As ServiceHostBase) Implements IServiceBehavior.ApplyDispatchBehavior
  Console.WriteLine("The EnforceGreetingFaultBehavior has been applied.")
  For Each chanDisp As ChannelDispatcher In serviceHostBase.ChannelDispatchers
    chanDisp.ErrorHandlers.Add(Me)
  Next chanDisp
End Sub

' This behavior requires that the contract have a SOAP fault with a detail type of GreetingFault.
Public Sub Validate(ByVal description As ServiceDescription, ByVal serviceHostBase As ServiceHostBase) Implements IServiceBehavior.Validate
  Console.WriteLine("Validate is called.")
  For Each se As ServiceEndpoint In description.Endpoints
    ' Must not examine any metadata endpoint.
    If se.Contract.Name.Equals("IMetadataExchange") AndAlso se.Contract.Namespace.Equals("http://schemas.microsoft.com/2006/04/mex") Then
      Continue For
    End If
    For Each opDesc As OperationDescription In se.Contract.Operations
      If opDesc.Faults.Count = 0 Then
        Throw New InvalidOperationException(String.Format("EnforceGreetingFaultBehavior requires a " & "FaultContractAttribute(typeof(GreetingFault)) in each operation contract.  " & "The ""{0}"" operation contains no FaultContractAttribute.", opDesc.Name))
      End If
      Dim gfExists As Boolean = False
      For Each fault As FaultDescription In opDesc.Faults
        If fault.DetailType.Equals(GetType(GreetingFault)) Then
          gfExists = True
          Continue For
        End If
      Next fault
      If gfExists = False Then
        Throw New InvalidOperationException("EnforceGreetingFaultBehavior requires a FaultContractAttribute(typeof(GreetingFault)) in an operation contract.")
      End If
    Next opDesc
  Next se
End Sub
#End Region

在此範例中,行為類別也會實作 System.ServiceModel.Configuration.BehaviorExtensionElement,使用它可以將服務行為插入應用程式組態檔,如下列程式碼範例的示範。

<configuration>
  <system.serviceModel>
    <services>
      <service 
        name="Microsoft.WCF.Documentation.SampleService"
        behaviorConfiguration="metaAndErrors">
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8080/SampleService"/>
          </baseAddresses>
        </host>
        <endpoint
          address=""
          binding="wsHttpBinding"
          contract="Microsoft.WCF.Documentation.ISampleService"
         />
        <endpoint
          address="mex"
          binding="mexHttpBinding"
          contract="IMetadataExchange"
         />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="metaAndErrors">
          <serviceDebug includeExceptionDetailInFaults="true"/>
          <serviceMetadata httpGetEnabled="true"/>
          <enforceGreetingFaults />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <extensions>
      <behaviorExtensions>
        <add 
          name="enforceGreetingFaults" 
          type="Microsoft.WCF.Documentation.EnforceGreetingFaultBehavior, HostApplication, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"
        />
      </behaviorExtensions>
    </extensions>
  </system.serviceModel>
</configuration>

備註

實作 IServiceBehavior,以在應用程式層級修改、檢查或延伸服務執行的某些方面:

  • 您可以使用 ApplyDispatchBehavior 方法來變更執行階段屬性值或插入自訂延伸物件,例如錯誤處理常式、訊息或參數攔截器、安全性延伸或其他自訂延伸物件。

  • Validate使用 方法來檢查描述,再Windows Communication Foundation (WCF) 建構執行中的服務,以確認它可以正確執行。

  • 您可以使用 AddBindingParameters 方法,將服務的自訂資訊傳遞至繫結項目,以便能夠正確支援服務。

IServiceBehavior 物件可以利用其中任何一種方法,但通常只有一種是重要的;在這種情況下,未使用的方法不需任何值便可傳回。

注意

所有的 IServiceBehavior 方法都會傳遞 System.ServiceModel.Description.ServiceDescriptionSystem.ServiceModel.ServiceHostBase 物件當做參數。 ServiceDescription 參數僅供檢查之用;如果您修改這些物件,執行行為便沒有定義。

如果要執行預定的自訂工作,必須在建構服務執行階段之前將 IServiceBehavior 物件加入至 Behaviors 屬性。 有三種方式可以執行此動作:

WCF 中的服務行為範例包括 ServiceBehaviorAttribute 屬性、 System.ServiceModel.Description.ServiceThrottlingBehaviorSystem.ServiceModel.Description.ServiceDebugBehaviorSystem.ServiceModel.Description.ServiceMetadataBehavior 行為。

方法

AddBindingParameters(ServiceDescription, ServiceHostBase, Collection<ServiceEndpoint>, BindingParameterCollection)

提供將自訂資料傳遞到繫結項目以支援合約實作的功能。

ApplyDispatchBehavior(ServiceDescription, ServiceHostBase)

提供功能以變更執行階段屬性值或插入自訂延伸物件,例如錯誤處理常式、訊息或參數攔截器、安全性延伸或其他自訂延伸物件。

Validate(ServiceDescription, ServiceHostBase)

提供檢查服務主機和服務描述的功能,以確認服務能夠順利執行。

適用於