The most remarkable thing in WCF is its extensibility. The Indigo team did a really great work providing hooks almost everywhere, that allows to customize all behaviors in every step of the communication framework.
In this example I created a client behavior that communicates with a REST/POX service. Clemens Vasters have an excelent series of articles on how to create REST/POX services with WCF. There is also two articles here and there in MSDN but what I don't like about it is that you loose the type safe contracts, having to deal with
Message class in order to send a request or decode the response.
What I did to avoid this problem is use a series of extension points in order to customize the request and response messages. In the example I used the del.icio.us API.
These are the WCF hooks I've implemented:
- IEnpointBehavior: attaches the message inspector and also configures itself as an operation behavior in every contract operation.
- IOperationBehavior: configures the message formatter.
- IClientMessageInspector: customizes the request message suppressing the body, changing the HTTP method and headers, and setting the query string previously created by the message formatter. This is done setting an instance of
HttpRequestMessagePropertyin the message properties. This is later used by the HTTP channel.
- IClientMessageFormatter: This implements both the request and response customizations. In the
SerializeRequestmethod, it creates the query string and attach it as a property in an empty message. This is later used by the message inspector to create the final request. It also uses the
Actionvalue of the
OperationContractto use as the relative URI. In the
DeserializeReplymethod, the received message is deserialized as a plain XML using the
Once the behavior is attached to the client endpoint, the contract methods can be defined as:
[OperationContract(Action = "/v1/posts/recent")] PostsResponse GetRecentPosts(string tag, int? count);
That makes a request to the address defined in the
Action, with two arguments (tag and count) in the query string.
IMPORTANT NOTE: Take special care in the usage of this example. It doesn't take into account any of the important notes about the del.icio.us api usage, and you can be throttled. Use under your own risk. Again, this is just an example.
In order to use this example, first you have to provide your del.icio.us username and password to WCF, setting it in the
There is a number of things to improve. For example, right now it only supports GET requests. It should also handle POST method serializing the arguments as a POX request. Also, the query string arguments formatting should be customizable.
Download the sources: WcfRestPox.zip