FaultContractAttribute 類別

定義

指定當服務作業遇到處理錯誤時,所傳回的一或多個 SOAP 錯誤。Specifies one or more SOAP faults that are returned when a service operation encounters processing errors.

public ref class FaultContractAttribute sealed : Attribute
[System.AttributeUsage(System.AttributeTargets.Method, AllowMultiple=true, Inherited=false)]
public sealed class FaultContractAttribute : Attribute
type FaultContractAttribute = class
    inherit Attribute
Public NotInheritable Class FaultContractAttribute
Inherits Attribute
繼承
FaultContractAttribute
屬性

範例

下列程式碼範例將示範如何使用 FaultContractAttribute 來指定 SampleMethod 作業可以傳回 SOAP 錯誤,連同 GreetingFault 的詳細型別。The following code example shows the use of FaultContractAttribute to specify that the SampleMethod operation can return a SOAP fault with the detail type of GreetingFault.

using System;
using System.Collections.Generic;
using System.Net.Security;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace Microsoft.WCF.Documentation
{
  [ServiceContract(Namespace="http://microsoft.wcf.documentation")]
  public interface ISampleService{
    [OperationContract]
    [FaultContractAttribute(
      typeof(GreetingFault),
      Action="http://www.contoso.com/GreetingFault",
      ProtectionLevel=ProtectionLevel.EncryptAndSign
      )]
    string SampleMethod(string msg);
  }

  [DataContractAttribute]
  public class GreetingFault
  {
    private string report;

    public GreetingFault(string message)
    {
      this.report = message;
    }

    [DataMemberAttribute]
    public string Message
    {
      get { return this.report; }
      set { this.report = value; }
    }
  }

  class SampleService : ISampleService
  {
  #region ISampleService Members

  public string  SampleMethod(string msg)
  {
    Console.WriteLine("Client said: " + msg);
    // Generate intermittent error behavior.
    Random rnd = new Random(DateTime.Now.Millisecond);
    int test = rnd.Next(5);
    if (test % 2 != 0)
      return "The service greets you: " + msg;
    else
      throw new FaultException<GreetingFault>(new GreetingFault("A Greeting error occurred. You said: " + msg));
  }

  #endregion
  }
}

Imports System.Collections.Generic
Imports System.Net.Security
Imports System.Runtime.Serialization
Imports System.ServiceModel
Imports System.Text

Namespace Microsoft.WCF.Documentation
  <ServiceContract(Namespace:="http://microsoft.wcf.documentation")> _
  Public Interface ISampleService
    <OperationContract, FaultContractAttribute(GetType(GreetingFault), Action:="http://www.contoso.com/GreetingFault", ProtectionLevel:=ProtectionLevel.EncryptAndSign)> _
    Function SampleMethod(ByVal msg As String) As String
  End Interface

  <DataContractAttribute> _
  Public Class GreetingFault
    Private report As String

    Public Sub New(ByVal message As String)
      Me.report = message
    End Sub

    <DataMemberAttribute> _
    Public Property Message() As String
      Get
          Return Me.report
      End Get
      Set(ByVal value As String)
          Me.report = value
      End Set
    End Property
  End Class

  Friend Class SampleService
      Implements ISampleService
  #Region "ISampleService Members"

  Public Function SampleMethod(ByVal msg As String) As String Implements ISampleService.SampleMethod
    Console.WriteLine("Client said: " & msg)
    ' Generate intermittent error behavior.
    Dim rand As New Random(DateTime.Now.Millisecond)
    Dim test As Integer = rand.Next(5)
    If test Mod 2 <> 0 Then
      Return "The service greets you: " & msg
    Else
      Throw New FaultException(Of GreetingFault)(New GreetingFault("A Greeting error occurred. You said: " & msg))
    End If
  End Function

  #End Region
  End Class
End Namespace

下列程式碼範例顯示 ISampleService 的 WCF 用戶端會體驗此 SOAP 錯誤,做為 GreetingFault類型的 FaultException<TDetail>The following code example shows that WCF clients of ISampleService experience this SOAP fault as a FaultException<TDetail> of type GreetingFault.

using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using Microsoft.WCF.Documentation;

public class Client
{
  public static void Main()
  {
    // Picks up configuration from the config file.
    SampleServiceClient wcfClient = new SampleServiceClient();
    try
    {
      // Making calls.
      Console.WriteLine("Enter the greeting to send: ");
      string greeting = Console.ReadLine();
      Console.WriteLine("The service responded: " + wcfClient.SampleMethod(greeting));

      Console.WriteLine("Press ENTER to exit:");
      Console.ReadLine();

      // Done with service.
      wcfClient.Close();
      Console.WriteLine("Done!");
    }
    catch (TimeoutException timeProblem)
    {
      Console.WriteLine("The service operation timed out. " + timeProblem.Message);
      Console.ReadLine();
      wcfClient.Abort();
    }
    catch (FaultException<GreetingFault> greetingFault)
    {
      Console.WriteLine(greetingFault.Detail.Message);
      Console.ReadLine();
      wcfClient.Abort();
    }
    catch (FaultException unknownFault)
    {
      Console.WriteLine("An unknown exception was received. " + unknownFault.Message);
      Console.ReadLine();
      wcfClient.Abort();
    }
    catch (CommunicationException commProblem)
    {
      Console.WriteLine("There was a communication problem. " + commProblem.Message + commProblem.StackTrace);
      Console.ReadLine();
      wcfClient.Abort();
    }
  }
}

Imports System.ServiceModel
Imports System.ServiceModel.Channels
Imports Microsoft.WCF.Documentation

Public Class Client
  Public Shared Sub Main()
    ' Picks up configuration from the config file.
    Dim wcfClient As New SampleServiceClient()
    Try
      ' Making calls.
      Console.WriteLine("Enter the greeting to send: ")
      Dim greeting As String = Console.ReadLine()
      Console.WriteLine("The service responded: " & wcfClient.SampleMethod(greeting))

      Console.WriteLine("Press ENTER to exit:")
      Console.ReadLine()

      ' Done with service. 
      wcfClient.Close()
      Console.WriteLine("Done!")
    Catch timeProblem As TimeoutException
      Console.WriteLine("The service operation timed out. " & timeProblem.Message)
      Console.ReadLine()
      wcfClient.Abort()
    Catch greetingFault As FaultException(Of GreetingFault)
      Console.WriteLine(greetingFault.Detail.Message)
      Console.ReadLine()
      wcfClient.Abort()
    Catch unknownFault As FaultException
      Console.WriteLine("An unknown exception was received. " & unknownFault.Message)
      Console.ReadLine()
      wcfClient.Abort()
    Catch commProblem As CommunicationException
      Console.WriteLine("There was a communication problem. " & commProblem.Message + commProblem.StackTrace)
      Console.ReadLine()
      wcfClient.Abort()
    End Try
  End Sub
End Class

備註

使用 FaultContractAttribute 屬性來標記作業,以宣告一或多個特定的例外狀況,這些條件會加入至服務作業的 Web 服務描述語言(WSDL)描述,做為作業所傳回的明確 SOAP 錯誤訊息。Mark an operation with the FaultContractAttribute attribute to declare one or more specific exception conditions that are added to the Web Service Description Language (WSDL) description of the service operation as explicit SOAP fault messages returned by the operation.

在所有 Managed 應用程式中,處理錯誤由 Exception 物件表示。In all managed applications, processing errors are represented by Exception objects. 在以 SOAP 為基礎的應用程式(例如 Windows Communication Foundation (WCF)應用程式)中,服務方法會使用 SOAP 錯誤訊息來溝通處理錯誤資訊。In SOAP-based applications such as Windows Communication Foundation (WCF) applications, service methods communicate processing error information using SOAP fault messages. 因為 WCF 應用程式會在這兩種錯誤系統下執行,所以任何必須傳送至用戶端的 managed 例外狀況資訊都必須從例外狀況轉換成 SOAP 錯誤。Because WCF applications execute under both types of error systems, any managed exception information that must be sent to the client must be converted from exceptions into SOAP faults. 您可使用預設的服務例外狀況行為,或自行控制是否要將例外狀況對應到錯誤訊息,以及其對應方式。You can use the default service exception behaviors, or you can explicitly control whether -- and how -- exceptions are mapped to fault messages. 如需 WCF 應用程式中的例外狀況和 SOAP 錯誤的總覽,請參閱指定和處理合約和服務中的錯誤For an overview of exceptions and SOAP faults in WCF applications, see Specifying and Handling Faults in Contracts and Services.

建議服務作業使用 FaultContractAttribute,以正式指定用戶端在正常作業過程中預期會收到的所有 SOAP 錯誤。It is recommended that service operations use the FaultContractAttribute to formally specify all SOAP faults that a client can expect to receive in the normal course of an operation. 我們也建議 SOAP 錯誤只傳回用戶端應該知道的資訊,將資訊暴露的程度降至最低。It is also recommended that only that information a client must know is returned in a SOAP fault to minimize information disclosure.

  • Action 屬性控制錯誤訊息的動作。The Action property controls the action of the fault message.

  • DetailType 屬性會取得在錯誤訊息中序列化之詳細資料物件的型別。The DetailType property gets the type of the detail object serialized in the fault message.

  • NameNamespace 屬性分別控制錯誤訊息的名稱和命名空間。The Name and Namespace properties control the name and namespace, respectively, of the fault message.

  • HasProtectionLevel 指出錯誤訊息是否已指定保護層級,如果是,則 ProtectionLevel 屬性會控制該保護層級。The HasProtectionLevel indicates whether the fault message has a protection level specified, and if so, the ProtectionLevel property controls that level of protection.

警告

如果錯誤訊息攜帶敏感性資訊或可能導致安全性問題,強烈建議您設定 ProtectionLevel 屬性。If a fault message carries information that is sensitive or can lead to security problems, it is strongly recommended that the ProtectionLevel property be set.

在許多情況下,設定 ProtectionLevelEncryptAndSign 錯誤訊息就已足夠。For many scenarios setting ProtectionLevel to EncryptAndSign for fault messages is sufficient. 如需詳細資訊,請參閱瞭解保護層級For more details, see Understanding Protection Level.

若要從標記為 FaultContractAttribute的作業傳回指定的錯誤,當作業期間發生 managed 例外狀況時,會擲回一個 FaultException<TDetail> (其中類型參數是可序列化的錯誤資訊)。To return a specified fault from an operation marked with FaultContractAttribute, throw a FaultException<TDetail> (where the type parameter is the serializable error information) when the managed exception occurs during the operation. WCF 用戶端應用程式會將 SOAP 錯誤呈現為與用戶端執行中擲回的相同類型,也就是 FaultException<TDetail> (其中 typeparameter 是可序列化的錯誤資訊)。WCF client applications surface the SOAP fault as the same type as was thrown in the client implementation -- that is, as a FaultException<TDetail> (where the typeparameter is the serializable error information). FaultContractAttribute 只能用來指定雙向服務作業和非同步作業配對的 SOAP 錯誤;單向作業不支援 SOAP 錯誤,因此不支援 FaultContractAttributeThe FaultContractAttribute can be used only to specify SOAP faults for two-way service operations and for asynchronous operation pairs; one-way operations do not support SOAP faults and therefore do not support FaultContractAttribute.

注意

您可使用任何可序列化型別來傳遞錯誤資訊。You can use any serializable type to convey error information. 這個 WCF 版本中唯一的限制是 FaultContractAttribute 中指定的類型必須可由 System.Runtime.Serialization.DataContractSerializer序列化。The only restriction in this version of WCF is that types specified in a FaultContractAttribute must be serializable by the System.Runtime.Serialization.DataContractSerializer. 如需 DataContractSerializer 提供的序列化支援,請參閱資料合約序列化程式For the serialization support the DataContractSerializer provides, see Data Contract Serializer.

例如,若要指定用戶端可以預期包含 Int32的 SOAP 錯誤,請將該型別參數放在服務方法的 FaultContractAttribute 中。For example, to specify that clients can expect a SOAP fault that contains an Int32, place that type parameter in the FaultContractAttribute on your service method.

注意

下列程式碼範例不會設定 ProtectionLevelNameNamespace 屬性。The following code examples do not set the ProtectionLevel, Name, or Namespace properties.

[OperationContractAttribute]
[FaultContractAttribute(typeof(int))]
int Divide(int arg1, int arg2);
  <OperationContractAttribute(), FaultContractAttribute(GetType(Integer))> _
    Function Divide(ByVal arg1 As Integer, ByVal arg2 As Integer) As Integer
End Interface 'FCADemonstration

然後,在您的服務方法中,會擲回新的 FaultException<TDetail>,其中型別參數是包含錯誤資訊的型別(在上述案例中為 Int32)。Then, in your service method, throw a new FaultException<TDetail> where the type parameter is the type that contains the error information (in the above case, a Int32). 例如,For example:

throw new FaultException<int>(4);
Throw New FaultException(Of Integer)(4)

前述範例非常基本;幾乎所有資訊都可以使用 System.Int32 的程式碼傳遞,因此此詳細類型並不是最有用的。The preceding example is very basic; almost any information can be passed using an System.Int32 code, so this detail type is not the most useful. 一般來說,WCF 應用程式會以用戶端錯誤資訊需求的特定詳細類型來指定 SOAP 錯誤。Typically, WCF applications specify SOAP faults with detail types specific to the error information requirements of the client. 如需更完整的範例,請參閱<範例>一節。For a more complete example, see the Example section.

注意

如果您指定型別參數為 System.StringFaultException<TDetail>,則字串值會指派給用戶端應用程式中的 Detail 屬性;用戶端無法藉由呼叫 FaultException<TDetail>.ToString 方法來取得該字串。If you specify a FaultException<TDetail> where the type parameter is a System.String, the string value is assigned to the Detail property in the client application; clients cannot retrieve that string by calling the FaultException<TDetail>.ToString method. 若要在用戶端應用程式呼叫 Exception.ToString 時傳回字串值,請在該作業內擲回一個 System.ServiceModel.FaultException 例外狀況,並將字串傳遞給建構函式。To have the string value returned when the client application calls Exception.ToString, throw a System.ServiceModel.FaultException exception inside the operation and pass the string to the constructor.

若要在擲回例外狀況或 FaultException<TDetail> 時明確控制應用程式的行為,請在 System.ServiceModel.Description.IServiceBehaviorSystem.ServiceModel.Description.IContractBehaviorSystem.ServiceModel.Description.IEndpointBehavior 上執行 System.ServiceModel.Dispatcher.IErrorHandler 介面,並將它指派給 ChannelDispatcher.ErrorHandlers 屬性。To explicitly control the behavior of the application when an exception or FaultException<TDetail> is thrown, implement the System.ServiceModel.Dispatcher.IErrorHandler interface on an System.ServiceModel.Description.IServiceBehavior, System.ServiceModel.Description.IContractBehavior or System.ServiceModel.Description.IEndpointBehavior and assign it to the ChannelDispatcher.ErrorHandlers property. IErrorHandler 可讓您明確地控制產生的 SOAP 錯誤,以及是否要將它傳回給用戶端。IErrorHandler enables you to explicitly control the SOAP fault that is generated and whether to send it back to the client.

若要加速偵錯工具,請將程式碼中的 ServiceBehaviorAttribute.IncludeExceptionDetailInFaults 設定為 true,或您可以在應用程式佈建檔中使用該 ServiceDebugBehavior.IncludeExceptionDetailInFaultsTo facilitate debugging, set the ServiceBehaviorAttribute.IncludeExceptionDetailInFaults to true in code or you can use the ServiceDebugBehavior.IncludeExceptionDetailInFaults in an application configuration file. 啟用時,服務會自動將例外狀況資訊傳回給呼叫者。When enabled, the service automatically returns exception information to the caller. 這些錯誤會以 FaultException 例外狀況的形式顯示給用戶端。These faults appear to the client as FaultException exceptions.

重要

因為 managed 例外狀況可以公開內部應用程式資訊,所以將 ServiceBehaviorAttribute.IncludeExceptionDetailInFaultsServiceDebugBehavior.IncludeExceptionDetailInFaults 設定為 true 可以允許 WCF 用戶端取得內部服務作業例外狀況的相關資訊,包括個人標識或其他機密資訊。Because managed exceptions can expose internal application information, setting ServiceBehaviorAttribute.IncludeExceptionDetailInFaults or ServiceDebugBehavior.IncludeExceptionDetailInFaults to true can permit WCF clients to obtain information about internal service operation exceptions, including personally identifiable or other sensitive information.

因此,若您只是暫時對服務應用程式進行偵錯,才建議把 ServiceBehaviorAttribute.IncludeExceptionDetailInFaultsServiceDebugBehavior.IncludeExceptionDetailInFaults 設為 trueTherefore, setting ServiceBehaviorAttribute.IncludeExceptionDetailInFaults or ServiceDebugBehavior.IncludeExceptionDetailInFaults to true is only recommended as a way of temporarily debugging a service application. 此外,若某個方法以這種方式傳回未處理的 Managed 例外狀況,則該方法的 WSDL 不會包含 FaultException<TDetail> 型別之 String 的合約。In addition, the WSDL for a method that returns unhandled managed exceptions in this way does not contain the contract for the FaultException<TDetail> of type String. 用戶端必須預期會有未知的 SOAP 錯誤(以 System.ServiceModel.FaultException 物件的形式傳回 WCF 用戶端),才能正確取得偵錯工具資訊。Clients must expect the possibility of an unknown SOAP fault (returned to WCF clients as System.ServiceModel.FaultException objects) to obtain the debugging information properly.

建構函式

FaultContractAttribute(Type)

初始化 FaultContractAttribute 類別的新執行個體。Initializes a new instance of the FaultContractAttribute class.

屬性

Action

取得或設定 SOAP 錯誤訊息的動作,此訊息指定為作業合約的一部分。Gets or sets the action of the SOAP fault message that is specified as part of the operation contract.

DetailType

取得包含錯誤資訊的可序列化物件型別。Gets the type of a serializable object that contains error information.

HasProtectionLevel

取得指出 SOAP 錯誤訊息是否已指派保護層級的值。Gets a value that indicates whether the SOAP fault message has a protection level assigned.

Name

取得或設定 Web 服務描述語言 (WSDL) 中的錯誤訊息名稱。Gets or sets the name of the fault message in Web Services Description Language (WSDL).

Namespace

取得或設定 SOAP 錯誤的命名空間。Gets or sets the namespace of the SOAP fault.

ProtectionLevel

指定 SOAP 錯誤從繫結要求的保護層級。Specifies the level of protection the SOAP fault requires from the binding.

TypeId

在衍生類別中實作時,取得這個 Attribute 的唯一識別碼。When implemented in a derived class, gets a unique identifier for this Attribute.

(繼承來源 Attribute)

方法

Equals(Object)

傳回值,這個值指出此執行個體是否與指定的物件相等。Returns a value that indicates whether this instance is equal to a specified object.

(繼承來源 Attribute)
GetHashCode()

傳回此執行個體的雜湊碼。Returns the hash code for this instance.

(繼承來源 Attribute)
GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(繼承來源 Object)
IsDefaultAttribute()

在衍生類別中覆寫時,表示這個執行個體的值是衍生類別的預設值。When overridden in a derived class, indicates whether the value of this instance is the default value for the derived class.

(繼承來源 Attribute)
Match(Object)

在衍生類別中覆寫時,會傳回值,表示這個執行個體是否等於指定物件。When overridden in a derived class, returns a value that indicates whether this instance equals a specified object.

(繼承來源 Attribute)
MemberwiseClone()

建立目前 Object 的淺層複製。Creates a shallow copy of the current Object.

(繼承來源 Object)
ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(繼承來源 Object)

明確介面實作

_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

將一組名稱對應至一組對應的分派識別項 (Dispatch Identifier)。Maps a set of names to a corresponding set of dispatch identifiers.

(繼承來源 Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

擷取物件的類型資訊,可以用來取得介面的類型資訊。Retrieves the type information for an object, which can be used to get the type information for an interface.

(繼承來源 Attribute)
_Attribute.GetTypeInfoCount(UInt32)

擷取物件提供的類型資訊介面數目 (0 或 1)。Retrieves the number of type information interfaces that an object provides (either 0 or 1).

(繼承來源 Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

提供物件所公開的屬性和方法的存取權。Provides access to properties and methods exposed by an object.

(繼承來源 Attribute)

適用於