Juan Wajnerman

Juan Wajnerman

REST/POX client with WCF

4 min
May 13 2007
4 min
May 13 2007

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 HttpRequestMessageProperty in the message properties. This is later used by the HTTP channel.
  • IClientMessageFormatter: This implements both the request and response customizations. In the SerializeRequest method, 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 Action value of the OperationContract to use as the relative URI. In the DeserializeReply method, the received message is deserialized as a plain XML using the XmlSerializer.

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

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