REST Client Library for Silverlight
I’ve been doing some hackery and ported the client libraries of the WCF REST Starter Kit to Silverlight. The library greatly simplifies things when it comes to accessing and consuming RESTful services and resources in your Silverlight application.
Here’s a sample for a simple GET using the HttpClient class:
public User GetUser(string userId) { //init client with base URI HttpClient client = new HttpClient(http://localhost:56789/users/); //send a HTTP GET request for a given resource HttpResponseMessage response = client.Get(userId); //parse the received data on the fly return response.Content.ReadAsDataContract<User>(); }
Or, in order to send a DTO via HTTP POST:
public void PostUser(User user) { //init client with base URI HttpClient client = new HttpClient("http://localhost:56789/"); //serialize user object HttpContent content = HttpContentExtensions.CreateDataContract(user); //post to user service HttpResponseMessage response = client.Post("/user", content); }
I have removed a few bits, but most of the functionality should be there, and I added “NOTE” comments to all the sections that I had to modify. I haven’t used this port in-depth but managed to access my RESTful resources as expected so far, and I hope it will work just fine as in most scenarios that are covered in the original Starter Kit. Of course, given the Starter Kit itself is prerelease software, this applies to this release even more.
Blocking vs. Async Operations
If you try to initiate a blocking request to your REST service on the UI thread, an InvalidOperationException is thrown due to synchronization issues. Accordingly, a snippet as the one above should always be invoked on a worker thread (which is a best practice anyway).
However, in order to simplify things, I’ve added a bunch of XXXAsync extension methods for the HttpClient class that allow you to invoke HTTP operations such as GET, POST, PUT etc. directly on the UI thread, and have the result delivered back to you through a simple callback action. Here’s the same snippet as above, this time using the GetAsync method of the HttpClient class:
public void GetFolder() { HttpClient client = new HttpClient("http://localhost:56789/root"); //you can invoke the GetAsync method on a worker thread client.GetAsync(response => { VirtualFolder folder = response.Content.ReadAsDataContract<VirtualFolder>(); }); }
Note that the callback action will be invoked on a worker thread, so you might have to switch back to the UI thread if you want to modify your UI.
Oh yes: Use at your own risk 😉
Download REST Starter Kit for Silverlight
Current Version: 1.0.3, 2010.02.14