.NET Framework Class Library
FaultContractAttribute Class

Specifies one or more SOAP faults that are returned when a service operation encounters processing errors.

Inheritance Hierarchy
SystemObject
   SystemAttribute
    System.ServiceModelFaultContractAttribute

Namespace:   System.ServiceModel
Assembly:  System.ServiceModel (in System.ServiceModel.dll)
Syntax
<[%$TOPIC/ms576187_en-us_VS_110_2_0_0_0_0%]([%$TOPIC/ms576187_en-us_VS_110_2_0_0_0_1%].Method, AllowMultiple := True, Inherited := False)> _
Public NotInheritable Class FaultContractAttribute _
	Inherits [%$TOPIC/ms576187_en-us_VS_110_2_0_0_0_2%]
[[%$TOPIC/ms576187_en-us_VS_110_2_0_1_0_0%]([%$TOPIC/ms576187_en-us_VS_110_2_0_1_0_1%].Method, AllowMultiple = true, Inherited = false)]
public sealed class FaultContractAttribute : [%$TOPIC/ms576187_en-us_VS_110_2_0_1_0_2%]
[[%$TOPIC/ms576187_en-us_VS_110_2_0_2_0_0%]([%$TOPIC/ms576187_en-us_VS_110_2_0_2_0_1%]::Method, AllowMultiple = true, Inherited = false)]
public ref class FaultContractAttribute sealed : public [%$TOPIC/ms576187_en-us_VS_110_2_0_2_0_2%]
[<[%$TOPIC/ms576187_en-us_VS_110_2_0_3_0_0%]>]
[<[%$TOPIC/ms576187_en-us_VS_110_2_0_3_0_1%]([%$TOPIC/ms576187_en-us_VS_110_2_0_3_0_2%].Method, AllowMultiple = true, Inherited = false)>]
type FaultContractAttribute =  
    class 
        inherit [%$TOPIC/ms576187_en-us_VS_110_2_0_3_0_3%] 
    end

The FaultContractAttribute type exposes the following members.

Constructors
  NameDescription
Public method Supported by Portable Class Library Supported in .NET for Windows Store apps FaultContractAttributeInitializes a new instance of the FaultContractAttribute class.
Top
Properties
  NameDescription
Public property Supported by Portable Class Library Supported in .NET for Windows Store apps ActionGets or sets the action of the SOAP fault message that is specified as part of the operation contract.
Public property Supported by Portable Class Library Supported in .NET for Windows Store apps DetailTypeGets the type of a serializable object that contains error information.
Public property HasProtectionLevelGets a value that indicates whether the SOAP fault message has a protection level assigned.
Public property Supported by Portable Class Library Supported in .NET for Windows Store apps NameGets or sets the name of the fault message in Web Services Description Language (WSDL).
Public property Supported by Portable Class Library Supported in .NET for Windows Store apps NamespaceGets or sets the namespace of the SOAP fault.
Public property ProtectionLevelSpecifies the level of protection the SOAP fault requires from the binding.
Public property TypeIdWhen implemented in a derived class, gets a unique identifier for this Attribute. (Inherited from Attribute.)
Top
Methods
  NameDescription
Public method Supported by Portable Class Library Supported in .NET for Windows Store apps EqualsInfrastructure. Returns a value that indicates whether this instance is equal to a specified object. (Inherited from Attribute.)
Public method Supported by Portable Class Library Supported in .NET for Windows Store apps GetHashCodeReturns the hash code for this instance. (Inherited from Attribute.)
Public method Supported by Portable Class Library Supported in .NET for Windows Store apps GetTypeGets the Type of the current instance. (Inherited from Object.)
Public method IsDefaultAttributeWhen overridden in a derived class, indicates whether the value of this instance is the default value for the derived class. (Inherited from Attribute.)
Public method MatchWhen overridden in a derived class, returns a value that indicates whether this instance equals a specified object. (Inherited from Attribute.)
Public method Supported by Portable Class Library Supported in .NET for Windows Store apps ToStringReturns a string that represents the current object. (Inherited from Object.)
Top
Explicit Interface Implementations
  NameDescription
Explicit interface implemetation Private method _AttributeGetIDsOfNamesMaps a set of names to a corresponding set of dispatch identifiers. (Inherited from Attribute.)
Explicit interface implemetation Private method _AttributeGetTypeInfoRetrieves the type information for an object, which can be used to get the type information for an interface. (Inherited from Attribute.)
Explicit interface implemetation Private method _AttributeGetTypeInfoCountRetrieves the number of type information interfaces that an object provides (either 0 or 1). (Inherited from Attribute.)
Explicit interface implemetation Private method _AttributeInvokeProvides access to properties and methods exposed by an object. (Inherited from Attribute.)
Top
Remarks

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.

In all managed applications, processing errors are represented by Exception objects. In SOAP-based applications such as Windows Communication Foundation (WCF) applications, service methods communicate processing error information using SOAP fault messages. 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. For an overview of exceptions and SOAP faults in WCF applications, see Specifying and Handling Faults in Contracts and Services.

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. It is also recommended that only that information a client must know is returned in a SOAP fault to minimize information disclosure.

  • The Action property controls the action of the fault message.

  • The DetailType property gets the type of the detail object serialized in the fault message.

  • The Name and Namespace properties control the name and namespace, respectively, of the fault message.

  • The HasProtectionLevel indicates whether the fault message has a protection level specified, and if so, the ProtectionLevel property controls that level of protection.

Caution noteCaution

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.

For many scenarios setting ProtectionLevel to EncryptAndSign for fault messages is sufficient. For more details, see Understanding Protection Level.

To return a specified fault from an operation marked with FaultContractAttribute, throw a FaultExceptionTDetail (where the type parameter is the serializable error information) when the managed exception occurs during the operation. WCF client applications surface the SOAP fault as the same type as was thrown in the client implementation -- that is, as a FaultExceptionTDetail (where the typeparameter is the serializable error information). The 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.

NoteNote

You can use any serializable type to convey error information. The only restriction in this version of WCF is that types specified in a FaultContractAttribute must be serializable by the System.Runtime.SerializationDataContractSerializer. For the serialization support the DataContractSerializer provides, see Data Contract Serializer.

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.

NoteNote

The following code examples do not set the ProtectionLevel, Name, or Namespace properties.

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

Then, in your service method, throw a new FaultExceptionTDetail where the type parameter is the type that contains the error information (in the above case, a Int32). For example:

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

The preceding example is very basic; almost any information can be passed using an SystemInt32 code, so this detail type is not the most useful. 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.

NoteNote

If you specify a FaultExceptionTDetail where the type parameter is a SystemString, the string value is assigned to the Detail property in the client application; clients cannot retrieve that string by calling the FaultExceptionTDetailToString method. To have the string value returned when the client application calls ExceptionToString, throw a System.ServiceModelFaultException exception inside the operation and pass the string to the constructor.

To explicitly control the behavior of the application when an exception or FaultExceptionTDetail is thrown, implement the System.ServiceModel.DispatcherIErrorHandler interface on an System.ServiceModel.DescriptionIServiceBehavior, System.ServiceModel.DescriptionIContractBehavior or System.ServiceModel.DescriptionIEndpointBehavior and assign it to the ChannelDispatcher.Errorhandlers property. IErrorHandlerenables you to explicitly control the SOAP fault that is generated and whether to send it back to the client.

To facilitate debugging, set the ServiceBehaviorAttributeIncludeExceptionDetailInFaults to true in code or you can use the ServiceDebugBehaviorIncludeExceptionDetailInFaults in an application configuration file. When enabled, the service automatically returns exception information to the caller. These faults appear to the client as FaultException exceptions.

Important noteImportant

Because managed exceptions can expose internal application information, setting ServiceBehaviorAttributeIncludeExceptionDetailInFaults or ServiceDebugBehaviorIncludeExceptionDetailInFaults to true can permit WCF clients to obtain information about internal service operation exceptions, including personally identifiable or other sensitive information.

Therefore, setting ServiceBehaviorAttributeIncludeExceptionDetailInFaults or ServiceDebugBehaviorIncludeExceptionDetailInFaults to true is only recommended as a way of temporarily debugging a service application. In addition, the WSDL for a method that returns unhandled managed exceptions in this way does not contain the contract for the FaultExceptionTDetail of type String. Clients must expect the possibility of an unknown SOAP fault (returned to WCF clients as System.ServiceModelFaultException objects) to obtain the debugging information properly.

Examples

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.

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

The following code example shows that WCF clients of ISampleService experience this SOAP fault as a FaultExceptionTDetail of type GreetingFault.

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
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();
    }
  }
}
Version Information

.NET Framework

Supported in: 4.5.1, 4.5, 4, 3.5, 3.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

.NET for Windows Store apps

Supported in: Windows 8

.NET for Windows Phone apps

Supported in: Windows Phone 8.1, Windows Phone 8, Silverlight 8.1
Platforms

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Thread Safety
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.