Windows Communication Foundation (WCF) is a framework for building service-oriented applications. Using WCF, you can send data as asynchronous messages from one service endpoint to another. It is designed using service-oriented architecture principles to support distributed computing where services have remote consumers. Clients can consume multiple services; services can be consumed by multiple clients. A service endpoint can be part of a continuously available service hosted by IIS, or it can be a service hosted in an An endpoint can be a client of a service that requests data from a service endpoint. The messages can be as simple as a single character or word sent as XML, or as complex as a stream of binary data. A few sample scenarios include: A secure service to process business transactions. A service that supplies current data to others, such as a traffic report or other monitoring service. A chat service that allows two people to communicate or exchange data in real time. A dashboard application that polls one or more services for data and presents it in a logical presentation. Exposing a workflow implemented using Windows Workflow Foundation as a WCF service. A Silverlight application to poll a service for the latest data feeds.
Web Services | |
ASMX web service is designed to send and receive messages using SOAP over HTTP only | WCF service can exchange messages using any format (SOAP is default) over any transport protocol (HTTP, TCP/IP, MSMQ, Named Pipes etc). |
Uses XML Serialization | Data Contract Serialization |
Hosted IIS Only | Hosted in IIS, WAS (Windows Active service), Self-Host, and Console/Windows apps |
Limited security | Consistent security models (WS-*) WS-Security, WS-Addressing, WS-Reliable Messaging, WS-Interoperability, WS-Transaction) |
Once service is ready, clients need information about service to communicate with it. This is where service endpoints come into picture.
A service endpoint has three parts or also called ABCs of an endpoint i.e. Address, Binding and Contract.
Address: It defines “WHERE”. URL of the service location
Binding: It defines “HOW”. How a client can communicate with the endpoint? Example HTTP, HTTPS, TCP or MSMQ etc.?
Contract: It defines “WHAT”. What is the business logic behind the service?
One more important part is Behaviors - A set of behaviors that specify local implementation details of the endpoint.
Bindings in WCF actually defines that how to communicate with the service. Binding specifies that what communication protocol as well as encoding method will be used. Optionally, binding can specify other important factors like transactions, reliable sessions and security. Another WCF Tutorial gives more detailed understanding of Binding concept in WCF. There are different built-in bindings available in WCF, each designed to fulfill some specific need.
basicHttpBinding Basic Web service communication. No security by default wsHttpBinding Web services with WS-* support. Supports transactions webHttpBinding Defines a binding element that is used to configure endpoints for WCF Web services that respond to HTTP requests instead of SOAP messages. wsDualHttpBinding Web services with duplex contract and transaction support wsFederationHttpBinding Web services with federated security. Supports transactions msmqIntegrationBinding Communication directly with MSMQ applications. Supports transactions netMsmqBinding Communication between WCF applications by using queuing. Supports transactions netNamedPipeBinding Communication between WCF applications on same computer. Supports duplex contracts and transactions netPeerTcpBinding Communication between computers across peer-to-peer services. Supports duplex contracts netTcpBinding Communication between WCF applications across computers. Supports duplex contracts and transactions udpBinding A configuration element used to configure the UdpBinding binding (User Datagram Protocol). It's connectionless protocol runs on top of IP network. mexHttpBinding Specifies the settings for a binding used for the WS-MetadataExchange (WS-MEX) message exchange over HTTP customBinding Provides full control over the messaging stack for the user.
A Contract is basically an agreement between the two parties i.e. Service and Client. In WCF, Contracts can be categorized as behavioral or structural. Behavioral Contracts define that what operations client can perform on a service. ServiceContract => attribute is used to mark a type as Service contract that contains operations. OperationContract => attributes is used to mark the operations that will be exposed. Fault Contract => defines what errors are raised by the service being exposed. Structural Contracts DataContract => attribute define types that will be moved between the parties. MessageContract => attribute define the structure of SOAP message.
A data contract is a formal agreement between a service and a client that abstractly describes the data to be exchanged. WCF uses a serialization engine called the Data Contract Serializer by default to serialize and deserialize data (convert it to and from XML). All .NET Framework primitive types, such as integers and strings, as well as certain types treated as primitives, such as DateTime and XmlElement, can be serialized with no other preparation and are considered as having default data contracts. Many .NET Framework types also have existing data contracts New complex types that you create must have a data contract defined for them to be serializable. By default, the DataContractSerializer infers the data contract and serializes all publicly visible types. All public read/write properties and fields of the type are serialized.
[DataContract] public class PurchaseOrder { private int poId_value; // Apply the DataMemberAttribute to the property. [DataMember] public int PurchaseOrderId { get { return poId_value; } set { poId_value = value; } } }
Data Contracts: WCF data contracts provide a mapping function between .NET CLR types that are defined in code and XML Schemas Definitions defined by the W3C organization (www.w3c.org/) that are used for communication outside the service. It is an agreement between parties service and a client that describes what type of data will be exchanged between them It controls the contents that is message body or payload data Enable interoperability through the XML Schema Definition (XSD) standard Message Contracts: Message contracts describe the structure of SOAP messages sent to and from a service and enable you to inspect and control most of the details in the SOAP header and body. Enable you to interoperate with any system that communicates through SOAP Gives you complete control over the SOAP message sent to and from a service by providing access to the SOAP headers and bodies directly. This allows use of simple or complex types to define the exact content of the SOAP parts.
Passing information in SOAP headers is useful if you want to communicate information from the operation signature. For example 1.Session or correlation information can be passed in headers, rather than adding additional parameters to operations or adding this information as fields in the data itself. 2. It is security, where you may want to implement a custom security protocol (bypassing WS-Security) and pass credentials or tokens in custom SOAP headers.3. It is signing and encrypting SOAP headers, where you may want to sign and/or encrypt some or all header information. All these cases can be handled with message contracts. The downside with this technique is that the client and service must manually add and retrieve the information from the SOAP header, rather than having the serialization classes associated with data and operation contracts do it for you.
Because message-based programming and parameter-based programming cannot be mixed, so you cannot specify a DataContract as an input argument to an operation and have it returns a MessageContract, or specifies a MessageContract as the input argument to an operation and has it return a DataContract. You can mix typed and untyped messages, but not messageContracts and DataContracts. Mixing message and data contracts will cause a runtime error when you generate WSDL from the service. >
In order to generate proxy, we need service metadata and mexHttpBinding returns service metadata.
If we look into our configuration file, service will have an endpoint with mexHttpBinding as follows:
WCF supports three different types of Instance Activation methods:
There are three different ways to handle concurrency in WCF that are:
WCF throttling enables us to regulate the maximum number of WCF instances, concurrent calls and concurrent sessions. Basic purpose is to control our WCF service performance by using Service throttling behavior. In configuration file we can set this behavior as follows:
Above given values are the default ones, but we can update it after looking into the requirements of our application.
Normally, by default, when some exception occurs at a WCF service level, it will not expose as it is to client. Reason is that WCF exception is a CLR exception and it doesn’t make sense to expose it outside CLR because it contains internal details of service code like stack trace. So, WCF handles and returns error details to client using Fault Contract. “So, fault contract is a contract that contains the details of possible exception(s) that might occur in a service code.” [ServiceContract] public interface IService1 { [OperationContract] [FaultContract(typeof(MyFaultDetails))] int MyOperation1(); } [DataContract] public class MyFaultDetails { [DataMember] public string ErrorDetails { get; set; } } In implementing service….. public int MyOperation1() { Try{ //Do something…… }catch() { MyFaultDetails ex = new MyFaultDetails(); ex.ErrorDetails = “Specific error details here.“; throw new FaultException(ex,“Reason: Testing…..“); } } A user has a service with a one-way operation that includes a fault contract, and he gets an exception when he tries to host the service. Why?This is true, because, to return faults, the service requires some form of a two-way communication channel, which is not there with one-way operations.
There are four core security Features Confidentiality: It’s a confirmation about the recipient. Only the valid recipient can read the message when it passed between service and client. Integrity: is to ensure that message received is not being tempered or changed during exchange. Authentication: is a way for the parties (sender and receiver) to identify each other. Authorization: ensures that what actions an authenticated user can perform?
Security can be configured at different levels in Windows Communication Foundation. Transport Level Security secures the transport (the pipe) over which the message passes through from client to a service. Message Level Security secures the message that is being transported from one end to another.