How to: Declare Faults in Service Contracts
Collapse the table of content
Expand the table of content

How to: Declare Faults in Service Contracts


In managed code, exceptions are thrown when error conditions occur. In Windows Communication Foundation (WCF) applications, however, service contracts specify what error information is returned to clients by declaring SOAP faults in the service contract. For an overview of the relationship between exceptions and faults, see Specifying and Handling Faults in Contracts and Services.

Create a service contract that specifies a SOAP fault

  1. Create a service contract that contains at least one operation. For an example, see How to: Define a Windows Communication Foundation Service Contract.

  2. Select an operation that can specify an error condition about which clients can expect to be notified. To decide which error conditions justify returning SOAP faults to clients, see Specifying and Handling Faults in Contracts and Services.

  3. Apply a System.ServiceModel.FaultContractAttribute to the selected operation and pass a serializable fault type to the constructor. For details about creating and using serializable types, see Specifying Data Transfer in Service Contracts. The following example shows how to specify that the SampleMethod operation can result in a GreetingFault.

    string SampleMethod(string msg);
  4. Repeat steps 2 and 3 for all operations in the contract that communicate error conditions to clients.

Once an operation has specified that a specific SOAP fault can be returned (such as in the preceding procedure) to communicate an error condition to a calling application, the next step is to implement that specification.

Throw the specified SOAP fault in the operation

  1. When a FaultContractAttribute-specified error condition occurs in an operation, throw a new System.ServiceModel.FaultException<TDetail> where the specified SOAP fault is the type parameter. The following example shows how to throw the GreetingFault in the SampleMethod shown in the preceding procedure and in the following Code section.

    throw new FaultException<GreetingFault>(new GreetingFault("A Greeting error occurred. You said: " + msg));

The following code example shows an implementation of a single operation that specifies a GreetingFault for the SampleMethod operation.

// 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));
© 2015 Microsoft