FaultContractAttribute FaultContractAttribute FaultContractAttribute FaultContractAttribute Class

定义

指定服务操作遇到处理错误时返回的一个或多个 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
继承
FaultContractAttributeFaultContractAttributeFaultContractAttributeFaultContractAttribute
属性

示例

下面的代码示例演示如何使用 FaultContractAttribute 来指定 SampleMethod 操作可以使用详细信息类型 GreetingFault 返回 SOAP 错误。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
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

下面的代码示例演示的 WCF 客户端ISampleService作为此 SOAP 错误FaultException<TDetail>类型的GreetingFaultThe 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
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 属性标记操作以声明一个或多个特定的异常条件,这些条件可作为操作返回的显式 SOAP 错误消息添加到服务操作的 Web 服务描述语言 (WSDL) 的描述中。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.

在所有托管应用程序中,处理错误由 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 应用程序,必须从异常转化为 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.

在大多数情况下,将错误消息的 ProtectionLevel 设置为 EncryptAndSign 已经足够了。For many scenarios setting ProtectionLevel to EncryptAndSign for fault messages is sufficient. 有关更多详细信息,请参阅了解保护级别For more details, see Understanding Protection Level.

若要从使用 FaultContractAttribute 进行标记的操作返回指定的错误,则在操作过程中发生托管异常时将引发 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>(此处类型参数为可序列化的错误信息)。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.DataContractSerializerThe 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.

备注

如果指定一个类型参数为 FaultException<TDetail>System.String,则该字符串值将被分配给客户端应用程序中的 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.Dispatcher.IErrorHandlerSystem.ServiceModel.Description.IServiceBehaviorSystem.ServiceModel.Description.IContractBehavior 上实现 System.ServiceModel.Description.IEndpointBehavior 接口,并将其分配给 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.IncludeExceptionDetailInFaultstrue中的代码也可以使用ServiceDebugBehavior.IncludeExceptionDetailInFaults应用程序配置文件中。To 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.

重要

因为托管的异常可以公开内部应用程序的信息,设置ServiceBehaviorAttribute.IncludeExceptionDetailInFaultsServiceDebugBehavior.IncludeExceptionDetailInFaultstrue可以允许 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 设置为 true 作为一种临时调试服务应用程序的方法。Therefore, setting ServiceBehaviorAttribute.IncludeExceptionDetailInFaults or ServiceDebugBehavior.IncludeExceptionDetailInFaults to true is only recommended as a way of temporarily debugging a service application. 此外,以这种方式返回未处理的托管异常的方法的 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 错误的可能性 (返回给 WCF 客户端作为System.ServiceModel.FaultException对象) 以便正确获取调试信息。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(Type) FaultContractAttribute(Type) FaultContractAttribute(Type)

初始化 FaultContractAttribute 类的新实例。Initializes a new instance of the FaultContractAttribute class.

属性

Action Action Action Action

获取或设置已指定作为操作协定一部分的 SOAP 错误消息的操作。Gets or sets the action of the SOAP fault message that is specified as part of the operation contract.

DetailType DetailType DetailType DetailType

获取包含错误信息的可序列化对象的类型。Gets the type of a serializable object that contains error information.

HasProtectionLevel HasProtectionLevel HasProtectionLevel HasProtectionLevel

获取一个值,该值指示 SOAP 错误消息是否分配有保护级别。Gets a value that indicates whether the SOAP fault message has a protection level assigned.

Name Name Name Name

获取或设置 Web 服务描述语言 (WSDL) 中的错误消息的名称。Gets or sets the name of the fault message in Web Services Description Language (WSDL).

Namespace Namespace Namespace Namespace

获取或设置 SOAP 错误的命名空间。Gets or sets the namespace of the SOAP fault.

ProtectionLevel ProtectionLevel ProtectionLevel ProtectionLevel

指定 SOAP 错误要求的绑定的保护级别。Specifies the level of protection the SOAP fault requires from the binding.

TypeId TypeId TypeId TypeId

在派生类中实现时,获取此 Attribute 的唯一标识符。When implemented in a derived class, gets a unique identifier for this Attribute.

(Inherited from Attribute)

方法

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

返回一个值,该值指示此实例是否与指定的对象相等。Returns a value that indicates whether this instance is equal to a specified object.

(Inherited from Attribute)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

返回此实例的哈希代码。Returns the hash code for this instance.

(Inherited from Attribute)
GetType() GetType() GetType() GetType()

获取当前实例的 TypeGets the Type of the current instance.

(Inherited from Object)
IsDefaultAttribute() IsDefaultAttribute() IsDefaultAttribute() IsDefaultAttribute()

在派生类中重写时,指示此实例的值是否是派生类的默认值。When overridden in a derived class, indicates whether the value of this instance is the default value for the derived class.

(Inherited from Attribute)
Match(Object) Match(Object) Match(Object) Match(Object)

当在派生类中重写时,返回一个指示此实例是否等于指定对象的值。When overridden in a derived class, returns a value that indicates whether this instance equals a specified object.

(Inherited from Attribute)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(Inherited from Object)
ToString() ToString() ToString() ToString()

返回表示当前对象的字符串。Returns a string that represents the current object.

(Inherited from Object)

显式界面实现

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

将一组名称映射为对应的一组调度标识符。Maps a set of names to a corresponding set of dispatch identifiers.

(Inherited from Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

检索对象的类型信息,然后可以使用该信息获取接口的类型信息。Retrieves the type information for an object, which can be used to get the type information for an interface.

(Inherited from Attribute)
_Attribute.GetTypeInfoCount(UInt32) _Attribute.GetTypeInfoCount(UInt32) _Attribute.GetTypeInfoCount(UInt32) _Attribute.GetTypeInfoCount(UInt32)

检索对象提供的类型信息接口的数量(0 或 1)。Retrieves the number of type information interfaces that an object provides (either 0 or 1).

(Inherited from Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

提供对某一对象公开的属性和方法的访问。Provides access to properties and methods exposed by an object.

(Inherited from Attribute)

适用于