FaultContractAttribute Class
Collapse the table of content
Expand the table of content

FaultContractAttribute Class


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

Namespace:   System.ServiceModel
Assembly:  System.ServiceModel (in System.ServiceModel.dll)


[AttributeUsageAttribute(AttributeTargets.Method, AllowMultiple = true, 
	Inherited = false)]
public sealed class FaultContractAttribute : Attribute


Initializes a new instance of the FaultContractAttribute class.


Gets or sets the action of the SOAP fault message that is specified as part of the operation contract.


Gets the type of a serializable object that contains error information.


Gets a value that indicates whether the SOAP fault message has a protection level assigned.


Gets or sets the name of the fault message in Web Services Description Language (WSDL).


Gets or sets the namespace of the SOAP fault.


Specifies the level of protection the SOAP fault requires from the binding.


When implemented in a derived class, gets a unique identifier for this Attribute.(Inherited from Attribute.)


This API supports the product infrastructure and is not intended to be used directly from your code. Returns a value that indicates whether this instance is equal to a specified object.(Inherited from Attribute.)


Returns the hash code for this instance.(Inherited from Attribute.)


Gets the Type of the current instance.(Inherited from Object.)


When overridden in a derived class, indicates whether the value of this instance is the default value for the derived class.(Inherited from Attribute.)


When overridden in a derived class, returns a value that indicates whether this instance equals a specified object.(Inherited from Attribute.)


Returns a string that represents the current object.(Inherited from Object.)

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

Maps a set of names to a corresponding set of dispatch identifiers.(Inherited from Attribute.)

System_CAPS_pubinterfaceSystem_CAPS_privmethod_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.)


Retrieves the number of type information interfaces that an object provides (either 0 or 1).(Inherited from Attribute.)

System_CAPS_pubinterfaceSystem_CAPS_privmethod_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Provides access to properties and methods exposed by an object.(Inherited from Attribute.)

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.


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 FaultException<TDetail> (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 FaultException<TDetail> (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.


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.Serialization.DataContractSerializer. 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.


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

int Divide(int arg1, int arg2);

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

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


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

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 P:System.ServiceModel.Dispatcher.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 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. These faults appear to the client as FaultException exceptions.


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.

Therefore, setting ServiceBehaviorAttribute.IncludeExceptionDetailInFaults or ServiceDebugBehavior.IncludeExceptionDetailInFaults 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 FaultException<TDetail> of type String. 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.

Legacy Code Example

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.

// This example signs an XML file using an
// envelope signature. It then verifies the 
// signed XML.
using System;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography.Xml;
using System.Text;
using System.Xml;

public class SignVerifyEnvelope

    public static void Main(String[] args)
           // Generate a signing key.
           RSACryptoServiceProvider Key = new RSACryptoServiceProvider();

           // Create an XML file to sign.
           Console.WriteLine("New XML file created."); 

           // Sign the XML that was just created and save it in a 
           // new file.
           SignXmlFile("Example.xml", "signedExample.xml", Key);
           Console.WriteLine("XML file signed."); 

           // Verify the signature of the signed XML.
           Console.WriteLine("Verifying signature...");
           bool result = VerifyXmlFile("SignedExample.xml", Key);

           // Display the results of the signature verification to 
           // the console.
               Console.WriteLine("The XML signature is valid.");
            Console.WriteLine("The XML signature is not valid.");
        catch(CryptographicException e)

    // Sign an XML file and save the signature in a new file. This method does not  
    // save the public key within the XML file.  This file cannot be verified unless  
    // the verifying code has the key with which it was signed.
    public static void SignXmlFile(string FileName, string SignedFileName, RSA Key)
        // Create a new XML document.
        XmlDocument doc = new XmlDocument();

        // Load the passed XML file using its name.
        doc.Load(new XmlTextReader(FileName));

        // Create a SignedXml object.
        SignedXml signedXml = new SignedXml(doc);

        // Add the key to the SignedXml document. 
        signedXml.SigningKey = Key;

        // Create a reference to be signed.
        Reference reference = new Reference();
        reference.Uri = "";

        // Add an enveloped transformation to the reference.
        XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();

        // Add the reference to the SignedXml object.

        // Compute the signature.

        // Get the XML representation of the signature and save
        // it to an XmlElement object.
        XmlElement xmlDigitalSignature = signedXml.GetXml();

        // Append the element to the XML document.
        doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));

        if (doc.FirstChild is XmlDeclaration)  

        // Save the signed XML document to a file specified
        // using the passed string.
        XmlTextWriter xmltw = new XmlTextWriter(SignedFileName, new UTF8Encoding(false));

    // Verify the signature of an XML file against an asymetric 
    // algorithm and return the result.
    public static Boolean VerifyXmlFile(String Name, RSA Key)
        // Create a new XML document.
        XmlDocument xmlDocument = new XmlDocument();

        // Load the passed XML file into the document. 

        // Create a new SignedXml object and pass it
        // the XML document class.
        SignedXml signedXml = new SignedXml(xmlDocument);

        // Find the "Signature" node and create a new
        // XmlNodeList object.
        XmlNodeList nodeList = xmlDocument.GetElementsByTagName("Signature");

        // Load the signature node.

        // Check the signature and return the result.
        return signedXml.CheckSignature(Key);

    // Create example data to sign.
    public static void CreateSomeXml(string FileName)
        // Create a new XmlDocument object.
        XmlDocument document = new XmlDocument();

        // Create a new XmlNode object.
        XmlNode  node = document.CreateNode(XmlNodeType.Element, "", "MyElement", "samples");

        // Add some text to the node.
        node.InnerText = "Example text to be signed.";

        // Append the node to the document.

        // Save the XML document to the file name specified.
        XmlTextWriter xmltw = new XmlTextWriter(FileName, new UTF8Encoding(false));

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();
      // 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:");

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

Universal Windows Platform
Available since 4.5
.NET Framework
Available since 3.0
Portable Class Library
Supported in: portable .NET platforms
Available since 3.0
Windows Phone Silverlight
Available since 7.0

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

Return to top
© 2015 Microsoft