Friday 27 November 2009

SilverLight RESTing on Windows Communication Foundation (WCF)

1. Build the WCF service
A few things to keep in mind when building the service using REST:
a. Use the WebHttpBinding to expose the service

<endpoint address="services/rest" binding="webHttpBinding" bindingConfiguration="MyRestServiceBinding"

contract="_Corp_.Services.Rest.IRestService"

behaviorConfiguration="webHttpBehavior"/>


b. Use appropriate [WebGet] and [WebInvoke] attributes on operations of your service contract

[OperationContract]

[WebGet(UriTemplate = "/uppercase?value={value}")]

string GetUpperCaseString(string value);


c. To avoid cross domain issues while consuming the WCF service from the Silverlight, the WCF service must somehow define its client access policy.
i. If the service is hosted in IIS, this client access policy defined in a ClientAccessPolicy.xml file must be placed at the ROOT of the web site. Placing this file at the same level as the web application does not work.

ii. During development, most of the time the service is hosted by Visual Studio. In this case, you don’t have a web server where you can simply drop the client access policy file at the root of the web site hosting your web service. One solution to this problem is to expose a service endpoint with a WebHttpBinding which will provide the client access policy to Silverlight client applications.

<!-- The client access policy SHOULD be exposed at the ROOT of the HOST (Web server / VS studio host , etc) -->

<endpoint address="" binding="webHttpBinding" bindingConfiguration="MyRestServiceBinding" contract="_Corp_.Services.Rest.IClientAccessPolicy" behaviorConfiguration="webHttpBehavior" />


[ServiceContract(Namespace = Constant.ServiceNamespace200911)]

public interface IClientAccessPolicy

{

[OperationContract]

[WebGet(UriTemplate = "/clientaccesspolicy.xml")]

Stream GetClientAccessPolicy();

}

2. Consume the WCF service in REST mode from a Silverlight application

The REST WCF service can be consumed from a Silverlight application without generating a service proxy. The WebClient class can be used to directly to invoke a service operation by knowing the operation (resource) URI.


WebClient webClient = new WebClient();

webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);

webClient.DownloadStringAsync(new Uri("http://localhost:9090/services/rest/uppercase?value=sHaHmOhAmOd")));


A running sample can be made available on request. This sample has been constructed using:
- Visual Studio 2010 Beta 2
- .Net Framework 4.0 Beta 2
- Windows Communication Foundation (WCF) 4 Beta 2
- Silverlight 3

Enjoy.

Sh@h