Learning WCF

.Learning WCF


Learning WCF


Web page by Kevin Harris of Homer IL

Please contact Kevin Harris of Homer IL concerning this web site

"Windows Communication Foundation (WCF) is a framework for building service-oriented applications for the enterprise and the Web. WCF supports multiple protocols (TCP, HTTP, MSMQ, named pipes) and is designed to be extensible. WCF contains structures to ensure the integrity and security of the data along with reliable transmission."

This page is a review of the book, with additional notes, as I read through the chapters. This book covers Windows Communication Foundation (WCF) which is a Microsoft framework designed for building service-oriented applications for the enterprise and the web. WCF (.NET 3.0) services are highly interoperable and provide loose-coupling to allow disparate clients to access functionality across process and machine boundaries. WCF unifies programming methods used by its predecessors (.NET Remoting, ASMX services, Enterprise services) which were tightly coupled to particular technologies. In .NET 3.5 WCF added the ability to have HTTP WCF services. A more recent framework, Microsoft's Web API (.NET 4.0) specifically addresses the need for building RESTful web services which are based on HTTP. RESTful services are increasing in popularity as they are lightweight and scalable which allows them to also be accessed by lightweight mobile devices which have limited capabilities. Since HTTP support is ubiquitous, RESTful services are becoming quite popular. See the Evolvable Web APIs article for more information about Microsoft's Web API framework.

WCF is a development platform for service-oriented applications. Prior to WCF you would choose between .NET Remoting, ASMX services, and Enterprise Services to select the appropriate method of distributing business functionality. WCF provides a single programming model which contains the capabilities of all these previous technologies. With WCF you can cross process, machine, and corporate boundaries using a number of different protocols.

.Blue Indigo


Blue Indigo

Chapter 1: Hello Indigo

Indigo was the code name for the Windows Communication Foundation (WCF) framework which was released with Windows Vista as part of .NET 3.0. When released with .NET 3.0, WCF would run on Vista, XP(SP2), Windows Server 2003, and Windows Server 2008. WCF has been supported on each subsequent release of .NET and is widely used for creating services that allowing the sharing of business functionality across process and machine boundaries. The sharing of business functionality through networks to disparate clients was driven by the need to create complex enterprise systems and became known as Service Oriented Architecture (SOA).

"Service Oriented Architecture (SOA) is a paradigm for organizing and utilizing distributed capabilities that may be under the control of different ownership domains."

Getting to SOA was an evolution in design. Prior or SOA a Component-Oriented Programming model was used which shared binaries that encapsulated reusable classes. This was initially limited to the same machine until distributions technologies like COM, DCOM, and CORBA made it possible to boundaries. However component-oriented programming was tightly-coupled to particular technologies. Components were developed which converted messages from one technology to another to allow disparate machines to communicate. However these methods were cumbersome and sometimes introduced multiple transformations between clients and components. The loose coupling between clients and services is one of the fundamental (generally agreed upon) tenets of SOA:

  1. Service boundaries are explicit - services are responsible for exposing a specific set of business functionality throught a well-defined contract.

  2. Services are autonomous - services should be able to perform key functions without external dependencies (a.k.a. atomicity).

  3. Clients and services share contracts, not code - languages such as Web Services Description Languages (WSDL) are used to create discoverable contract documents which specify how data and functionality are accessed.

  4. Compatibility is based on policy - policy is a way to publish access constraints (supported protocols, security requirements, etc.) in a way tha clients can be aware of them and invoke services in a compatible manner. Policy is actually an extension of WSDL.

WCF is a development platform for service-oriented applications. Prior to WCF you would choose between .NET Remoting, ASMX services, and Enterprise Services to select the appropriate method of distributing business functionality. WCF provides a single programming model which contains the capabilities of all these previous technologies. With WCF you can configure services to cross process, machine, and corporate boundaries using a number of different protocols. WCF contains the plumbing for security, transactions, and reliable messaging over any protocol.

Terms

  • Service - an entry point or "window" through which business functionality can be reached.
  • SOAP - (Simple Object Access Protocol) is a messaging protocol. SOAP specifies how to encode XML-based messages used to communicate and interoperate over the web.
  • Remote Procedure Call (RPC) - a technology for creating distributed client/server programs. RPC is an interprocess communication technique that allows client and server software to communicate. RPC predates CORBA and DCOM, which predates WCF and RESTful services. RPC used binaries for communication which varied between technology stacks; so they were not interoperable as the newer communication techniques which use common formats such as XML and JSON.
  • ServiceHost - is part of the service model and is responsible for initializing communication channels that receive messages to a service. In .NET a WCF ServiceHost class is used to configure and expose a service for use by client applications when you are not using Internet Information Services (IIS) or Windows Activation Services (WAS) to expose a service. Use a ServiceHost object to load a service, configure endpoints, apply security settings, and start listeners to handle incoming requests.
  • Endpoints - provide clients access to the functionality that a WCF service offers. All communication with a WCF service occurs through the endpoints. Each endpoint contains:
    • Address - refers to the URI where messages can be sent to the service. An address has a scheme, domain, port, and path in the format: scheme://domain[:port]/path.
    • Binding - indicates the protocols supported for sending messages. Transport protocols include: TCP, named pipes, HTTP, and MSMQ. Also includes messaging protocols related to security and reliability.
    • Contract - a platform-neutral and standard way of identifying the service methods exposed to the outside world. WCF defines four types of contracts:
      1. Service Contract - describes which operations the client can perform on the service.
      2. Data Contract - describes which data types are passed to and from the service.
      3. Fault Contract - defines the errors which are raised by the service and how the service handles and propagates error to its clients.
      4. Message Contract - describes the structure of messages which are send and received by the service.
  • Channel Stack - layers of channels through which messages must pass. Layers include a transport channel, message-encoding channel, and channels for security, reliability, and other features.
  • Behaviors - modifies the way messages are processed as they flow through the channel stack. Behaviors control many service model features such as authentication, authorization, transaction, and message throttling.

Lab1 - Three Projects: Service, Host, and Client

Create Service Contract and single operation in service (Class Library). Create console application (Host) to host the service. Create a console application (Client) to consume the service. Run Host project first followed by Client project. If get access denied error, open Visual Studio with "Run as Administrator" option.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
using System.ServiceModel;

namespace HelloIndigo
{
    [ServiceContract]
    public interface IHelloIndigoService
    {
        [OperationContract]
        string HelloIndigo();
    }

    public class HelloIndigoService : IHelloIndigoService
    {
        public string HelloIndigo()
        {
            return "Hello Indigo";
        }
    }

}


Service (Service.cs)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ServiceModel;

namespace Host
{
    class Program
    {
        static void Main(string[] args)
        {
            using (ServiceHost host = new ServiceHost(typeof(HelloIndigo.HelloIndigoService),
                new Uri("http://localhost:8000/HelloIndigo")))
            {
                host.AddServiceEndpoint(typeof(HelloIndigo.IHelloIndigoService),
                    new BasicHttpBinding(), "HelloIndigoService");
                host.Open();
                Console.WriteLine("Press <ENTER> to terminate the service host");
                Console.ReadLine();
            }
        }
    }
}


Host (Program.cs)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ServiceModel;

namespace Client
{
    [ServiceContract]
    public interface IHelloIndigoService
    {
        [OperationContract]
        string HelloIndigo();
    }

    class Program
    {
        static void Main(string[] args)
        {
            EndpointAddress ep = new
                EndpointAddress("http://localhost:8000/HelloIndigo/HelloIndigoService");
            IHelloIndigoService proxy = ChannelFactory<IHelloIndigoService>.CreateChannel(new BasicHttpBinding(), ep);

            string s = proxy.HelloIndigo();
            Console.WriteLine(s);
            Console.WriteLine("Press <ENTER> to terminate Client.");
            Console.ReadLine();
        }
    }
}


Client (Program.cs)

.Service Configuration Editor


Service Configuration Editor

Lab2 - Service with Service Configuration Editor

Create service using WCF Service Template (use .NET 3.5 in order to see WCF Service Template). Update contract and implement service logic. Use Service Configuration Editor to create end points (Service and Mex) in external configuration file (App.config). Create host and client to test the service.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
using System.ServiceModel;

namespace Host
{
    [ServiceContract]
    public interface IHelloIndigoService
    {
        [OperationContract]
        string HelloIndigo();
    }
}


IHelloIndigo.cs

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
namespace Host
{

    public class HelloIndigoService : IHelloIndigoService
    {
        public string HelloIndigo()
        {
            return "Hello Indigo";
        }
    }
}


HelloIndigo.cs

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  
    <system.serviceModel>
        <behaviors>
            <serviceBehaviors>
                <behavior name="serviceBehavior">
                    <serviceMetadata httpGetEnabled="true" />
                </behavior>
            </serviceBehaviors>
        </behaviors>
        <services>
            <service behaviorConfiguration="serviceBehavior" name="Host.HelloIndigoService">
                <endpoint address="HelloIndigoService" binding="basicHttpBinding"
                    name="basicHttp" contract="Host.IHelloIndigoService" />
                <endpoint binding="mexHttpBinding" name="mex" contract="IMetadataExchange" />
                <host>
                    <baseAddresses>
                        <add baseAddress="http://localhost:8000/Host/HelloIndigoService" />
                    </baseAddresses>
                </host>
            </service>
        </services>
    </system.serviceModel>
</configuration>


Host - App.Config

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
            <section name="Client.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
        </sectionGroup>
    </configSections>
    <applicationSettings>
        <Client.Properties.Settings>
            <setting name="serviceAddress" serializeAs="String">
                <value>http://localhost:8000/HelloIndigo/HelloIndigoService</value>
            </setting>
            <setting name="Client_localhost_HelloIndigoService" serializeAs="String">
                <value>http://localhost:8000/Host/HelloIndigoService/HelloIndigoService</value>
            </setting>
        </Client.Properties.Settings>
    </applicationSettings>
</configuration>


Client - App.Config

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;

namespace Host
{
    class Program
    {
        static void Main(string[] args)
        {
            using (ServiceHost host = new ServiceHost(typeof(HelloIndigoService)))
            {
                host.Open();
                Console.WriteLine("Press <ENTER> to terminate the host application");
                Console.ReadLine();
            }
        }
    }
}


Host - Program.cs

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
using System;
using System.Collections.Generic;
using System.Text;


namespace Client
{
    class Program
    {
        static void Main(string[] args)
        {
            localhost.HelloIndigoService proxy = new
                Client.localhost.HelloIndigoService();
            string s = proxy.HelloIndigo();
            Console.WriteLine(s);

            Console.WriteLine("Press <ENTER> to terminate Client.");
            Console.ReadLine();
        }
    }
}


Client - Program.cs

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?xml version="1.0" encoding="utf-8"?>
<wsdl:definitions xmlns:wsap="http://schemas.xmlsoap.org/ws/2004/08/addressing/policy" xmlns:wsa10="http://www.w3.org/2005/08/addressing" xmlns:tns="http://tempuri.org/" xmlns:msc="http://schemas.microsoft.com/ws/2005/12/wsdl/contract" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:wsx="http://schemas.xmlsoap.org/ws/2004/09/mex" xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy" xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:wsaw="http://www.w3.org/2006/05/addressing/wsdl" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="HelloIndigoService" targetNamespace="http://tempuri.org/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/">
  <wsdl:types>
    <xsd:schema targetNamespace="http://tempuri.org/Imports">
      <xsd:import schemaLocation="http://localhost:8000/Host/HelloIndigoService?xsd=xsd0" namespace="http://tempuri.org/" />
      <xsd:import schemaLocation="http://localhost:8000/Host/HelloIndigoService?xsd=xsd1" namespace="http://schemas.microsoft.com/2003/10/Serialization/" />
    </xsd:schema>
  </wsdl:types>
  <wsdl:message name="IHelloIndigoService_HelloIndigo_InputMessage">
    <wsdl:part name="parameters" element="tns:HelloIndigo" />
  </wsdl:message>
  <wsdl:message name="IHelloIndigoService_HelloIndigo_OutputMessage">
    <wsdl:part name="parameters" element="tns:HelloIndigoResponse" />
  </wsdl:message>
  <wsdl:portType name="IHelloIndigoService">
    <wsdl:operation name="HelloIndigo">
      <wsdl:input wsaw:Action="http://tempuri.org/IHelloIndigoService/HelloIndigo" message="tns:IHelloIndigoService_HelloIndigo_InputMessage" />
      <wsdl:output wsaw:Action="http://tempuri.org/IHelloIndigoService/HelloIndigoResponse" message="tns:IHelloIndigoService_HelloIndigo_OutputMessage" />
    </wsdl:operation>
  </wsdl:portType>
  <wsdl:binding name="basicHttp" type="tns:IHelloIndigoService">
    <soap:binding transport="http://schemas.xmlsoap.org/soap/http" />
    <wsdl:operation name="HelloIndigo">
      <soap:operation soapAction="http://tempuri.org/IHelloIndigoService/HelloIndigo" style="document" />
      <wsdl:input>
        <soap:body use="literal" />
      </wsdl:input>
      <wsdl:output>
        <soap:body use="literal" />
      </wsdl:output>
    </wsdl:operation>
  </wsdl:binding>
  <wsdl:service name="HelloIndigoService">
    <wsdl:port name="basicHttp" binding="tns:basicHttp">
      <soap:address location="http://localhost:8000/Host/HelloIndigoService/HelloIndigoService" />
    </wsdl:port>
  </wsdl:service>
</wsdl:definitions>


HelloIndigo.wsdl



Chapter 3: Bindings

Bindings are used to specify the transport, message-encoding, and other messaging protocol details required for clients and services to build the communication channel through which they communicate with each other. A binding is made up of a collection of binding elements. Each element describes some aspect of how the endpoint communicates with clients. A binding must include at least one transport binding element, at least one message-encoding binding element (which the transport binding element can provide by default), and any number of other protocol binding elements. The process that builds a runtime out of this description allows each binding element to contribute code to that runtime.

You can use the CustomBinding class when one of the system-provided bindings does not meet the requirements of your service. All bindings are constructed from an ordered set of binding elements. Custom bindings can be built from a set of system-provided binding elements or can include user-defined custom binding elements.

A binding contains three types of elements:

    Protocol - determine the security, reliability, context flow settings, or user-defined protocols to use with messages that are sent to the endpoint.
    Transport - determine the underlying transport protocol to use when sending messages to the endpoint, for example: HTTP,HTTPS,TCP,
    named pipes,or MSMQ
    Message - determine the wire encoding to use for messages that are sent to the endpoint, for example, text/XML, binary, or Message Transmission Optimization Mechanism (MTOM)

The following standard binding come with WCF:

Http Methods (Verbs)
Binding Description
BasicHttpBinding A web service binding used for compatibility with earlier web service stacks such as ASP.NET web services (ASMX).
WSHttpBinding A web service binding that supports the latest in interoperable web service standards (WS*) and is compatible with more recent web service stacks
WSDualHttpBinding A web service binding supporting WS* and two-way communication.
WSFederationHttpBinding A web service binding that supports WS* as it relates to federated and single sign-on security scenarios.
NetNamedPipeBinding A connection-oriented binding for communications on the same machine over named pipes.
NetTcpBinding A connection-oriented binding for communications across process and machine boundaries over TCP.
WebHttpBinding Used for creating WCF RESTful services.



BasicHttpBinding supports:

Transport Protocols: HTTP, HTTPS
Message Encoding: Text, MTOM
Message Version: SOAP 1.1, no addressing headers
Transport Security: SSL with Basic, Digest, Ntlm, Windows, or Certificate credentials
Message Security: SOAP Message Security
Duplex: No
Reliable Messaging: No
Transactions: No

WSHttpBinding supports:

Transport Protocols: HTTP, HTTPS
Message Encoding: Text, Mtom
Message Version: SOAP 1.2, WS-Addressing
Transport Security: SSL with Basic, Digest, Ntlm, Windows, or Certificate credentials
Message Security: SOAP Message Security, WS-Security, WS-Trust, WS-SecureConversation
Duplex: No
Reliable Messaging: Yes
Transactions: Yes

WSDualHttpBinding supports:

Transport Protocols: HTTP
Message Encoding: Text, Mtom
Message Version: SOAP 1.2, WS-Addressing
Transport Security: No
Message Security: SOAP Message Security, WS-Trust
Duplex: Yes
Reliable Messaging: Yes
Transactions: Yes

NetNamedPipeBinding supports:

Transport Protocols: Named pipes
Message Encoding: Binary
Message Version: SOAP 1.2, WS-Addressing 1.0
Transport Security: SSL
Message Security: No
Duplex: Yes
Reliable Messaging: No
Transactions: Yes

NetTcpBinding supports:

Transport Protocols: TCP
Message Encoding: Binary
Message Version: SOAP 1.2, WS-Addressing 1.0
Transport Security: SSL with Windows or Certificate credentials
Message Security: SOAP Message Security, WS-Trust, WS-SecureConversation
Duplex: Yes
Reliable Messaging: Yes
Transactions: Yes

Binding elements available to a custom Binding:

UnrecognizedPolicyAssertions - includes support for unrecognized policy assertions in the WSDL.

TransactionFlow -transaction protocol settings beyond the standard bindings.

ReliableSession -reliable messaging protocol settings beyond the standard bindings.

Security - security settings beyond the standard bindings.

CompositeDuplex - adds two-way messaging support to the channel. Required for callback support with nonduplex transports such as HTTP.

OneWay - configures the transport protocol for the channel stack. Additional settings for one-way calls.

SslStreamSecurity, WindowsStreamSecurity - security settings for SSL or Windows transport security on top of the transport protocol.

BinaryMessageEncoding, MtomMessageEncoding, TextMessageEncoding - configures the wire format of messages.

TcpTransport, HttpTransport, HttpsTransport, PeerTransport, MsmqTransport - configures the transport protocol for the channel stack.



Chapter 7: Security

WCF contains an extensive environment for controlling security features through configuration (*app.config/web.config)The set of fundamental security concepts applicable to all distributed messaging systems includes:

  • Authentication - typically involves identifying the message sender. However mutual authentication identifies both the message sender and receiver to prevent possible man-in-the-middle attacks. WCF authentication mechanisms supported include: Windows tokens, username/password, certificates, and tokens from federated systems.
  • Authorization - follows authentication, it determines the system resources and functionality the user is permitted to access. WCF authentication can be based on Windows roles, ASP.NET roles, or custom authorization policies.
  • Integrity - messages are digitally signed to ensure they have not been altered in transit.
  • Confidentiality - sensitive messages, or message parts, are encrypted to be sure they can not be openly viewed if intercepted in transit.

* From: When configuring a service in Visual Studio, use either a Web.config file or an App.config file to specify the settings. The choice of the configuration file name is determined by the hosting environment you choose for the service. If you are using IIS to host your service, use a Web.config file. If you are using any other hosting environment, use an App.config file.

** Starting with .NET Framework version 4, WCF comes with a new default configuration model that simplifies WCF configuration requirements. If you do not provide any WCF configuration for a particular service, the runtime automatically configures your service with some standard endpoints and default binding/behavior. In practice, writing configuration is a major part of programming WCF applications.

Security requirements for a WCF service (aka Security Policy) must be well-defined so that client applications can adhere to the requirements and provide the required credentials and message protection expected by the service. Security policy is defined by the bindings used for each service endpoint (negotiating service credentials, secure sessions, signing and encryption algorithms) and by the interoperable WS-SecurityPolicy standards. Security policy is exposed in a service's WSDL document so tools such as SvcUtil can generate proxies and relevant configurations for clients. By default, SvcUtil automatically generates the proxy and configurations whenever a service reference is added.

For communications behind the firewall (eg Intranet Apps) TCP with binary message encoding can be used (TCP is reliable and faster than HTTP). For Internet access HTTP with text or MTOM encoding (depending on message size) can be used. WCF has a standard set of bindings (eg BasicHttpBinding, WSHtttpBinding, NetTcpBinding, etc) used for various situations and these standard bindings have different defaults and options for securing services. The default values can be overridden by specifying different values for configuration options, such as Security Mode and Credentials.

Different bindings have different options, but across all service bindings the possible security modes include:

  • None - turn security off (not recommended).

  • Transport - secure authentication and message protection is handled at the lower TCP level. This secures the transport (ie the pipe) through which the message travels. Transport provides only point-to-point channel security (i.e. intermediary servers, such as load balancers or reverse proxies have access to the message contents), so Transport is best used when both client and service resides on same intranet. Transport secures the network protocol, so no extra coding required. Transport does not use WS-Security, so clients and servers do not need to know how to handle WS-Security. Hardware accelerators can be used with Transport to improve performance.

  • Message - security information is passed in within the SOAP message. This secures the message itself that is being transported. Message is based on the interoperable W-Security standards and provides end-to-end channel security. In most cases Message security also uses certificates to provide encryption and signing. Messaging is usually slower than Transport. Message can support multiple transport options. Each message incurs the cost of encrypting/decrypting the message. Requires both client and server support WS-Security so does not support older technologies like ASMX.

  • TransportWithMessageCredential - credentials are passed with the SOAP message and message protection and server authentication are handled at the TCP level.



Chapter 8: Exceptions and Faults

To report an exception from a service to its caller,the exception must be serialized to a known format and wrapped in a message. SOAP 1.1 and SOAP 1.2 both define a format for faults which essentially contain similar information when serialized.

The following standard binding come with WCF:

SOAP Fault Formats
SOAP 1.1
SOAP 1.2 Description
faultcode Code Required. Can be one of the specification’s predefined codes or a custom code for the application.
faultstring Reason Required. String explanation of the fault. SOAP 1.2 supports multiple reasons for multilingual support.
faultactor Role Optional. Required for all SOAP nodes except for the ultimate receiver. A URI describing the source of the fault.
detail Detail Optional. Required if the SOAP body could not be processed. Should provide information about the body element(s) that failed.

WCF contains several exception types. Most of the WCF exception types are derived from a common base type, CommunicationException. Among those exception types, FaultException is the most important.

Exception => SystemException => CommunicationException => FaultException => FaultException

You can create a new instance of FaultException, or the CreateFault() method will return instance of FaultException. You can also use FaultException which will have a strongly typed details section. FaultException generates a MessageFault which is a runtime representation of a SOAP fault. If exceptions in the Service are not handled, they will propagate up the the service model which will fault the channel and return a less meaningful fault to the client.

Common exceptions that the clients should be prepared to handle include:

  • CommunicationException - If you trap this exception, you will trap most exceptions related to service model communications.
  • EndpointNotFoundException - Is thrown when the service endpoint cannot be found,usually because the address is incorrect.
  • TimeoutException - Arise when service operations run longer than the allotted receive timeout for the binding,or when the client cannot reach the remote service within the configured send timeout.

By default, the service model does not return the details of an uncaught exception when it returns a fault to the client, because doing so would present a security risk. However, WCF does provide an opt-in debugging behavior which will report exception details. This is generally set in the configuration file so it can be easily disabled without modifying the code.

In Configuration:


In Code:
[ServiceBehavior(IncludeExceptionDetailInFaults=true)]

Services which allow exceptions to propogate to the service model will fault the service channel, which tears down any client application sessions,
transport sessions,reliable sessions,or secure sessions. A recommended practice is to catch the exceptions in the service code and decide if the exception is fatal to the service. Then if fatal to the service, the channel should be allowed to fault. If the exception is not fatal to the service, and is something which should be logged or reported to the client, then the service should throw a fault instead of an exception. Faults can be thrown with FaultException or FaultException and the MessageFault type can be used to initialize the fault with additional details for the SOAP fault.

Throwing a FaultException:

throw new FaultException("An invalid operation occurred.");

Throwing a FaultExeption:

throw new FaultException(
new InvalidOperationException(("An invalid operation occurred."),
new FaultReason(("Invalid operation."),
FaultCode.CreateReceiverFaultCode(
new FaultCode("InvalidOperationException")));

* Note: Wrapping an existing CLR exception type in FaultException may be useful for intranet applications where both sides are WCF since the exception type will be meaningful on both client and server. However if both client and server are not always WCF, a few data contracts with FaultException should be used, which will decouple the client/server and promotoe interoperability.

FaultExceptions represent fault exceptions at runtime, but they are wrapped in a MessageFault before serialization. MessageFault is a runtime abstraction of a SOAP fault. MessageFaults are mapped to SOAP 1.1 or 1.2 fault formats. You can use MessageFault to initialize the falut, you have greater control over the contents of the SOAP fault.

MessageFault mfault = MessageFault.CreateFault(new FaultCode("Server", new
FaultCode(String.Format("Server.{0}", error.GetType( ).Name))), new
FaultReason(error.Message), error);
FaultException fex = FaultException.CreateFault(mfault, typeof(InvalidOperationException));
throw fex;

To declare faults, the FaultContractAttribute is applied to the method declaration in the interface (i.e. service contract):

[OperationContract]
[FaultContract(typeof(myErrorException))]
void myServiceMethod();

the FaultContractAttributes can be stacked to declare all the supported faults.