6 - Data communication - HTTP-Based Services

HTTP-based services do not require to create a proxy class. You can access them directly using HTTP requests. Silverlight provides two methods for sending HTTP requests: WebClient and HttpWebRequest.
HTTP-based service
Both WebClient class and HttpWebRequest class in our demo application will request data from the same HTTP-based service. Please, follow these steps to create it:

1) In general, such servise can return data in different format including XML, JSON, RSS and others. To simplify the example our custom service will return data in the same format as the previous web services. To meet this requirement, add a new ASPX page into your web project root folder, name it GetUsers.aspx and then modify its code behind as follows:

2) Ensure the service is working by typing its full URL into your web browser. Try to add "search" URL parameter to specify some search expression.  You should see similar results as were reached by ASMX service:

Custom service output

Now you are ready to consume data of the service by WebClient and HttpWebRequest classes. Bellow you can find their implementation in our demo application.

WebClient implementation

In general, WebClient class provides common methods for sending data to and receiving data from a resource identified by a URI.

I am sure that most of you have already worked with its modification within .NET Framework.  As you can see, using WebClient class in Silverlight 2.0 is also straighforward and simple:

HttpWebRequest implementation
In general, HttpWebRequest class enables you to make a request to a specified URI.

Implementation requires more lines of code (HttpWebReqest uses an asynchronous programming model using delegates instead of the event-based asynchronous model of the WebClient class):


What's the difference? ... synchronization!

The WebClient callback, which is raised when the HTTP response is returned, is invoked on the UI thread. It means you can update the properties of the UI elements directly from the callback, synchronization is not required:

The HttpWebReqest callback is returned in the background thread so you need to synchronize it with the UI:
Synchronization required


This article is part of the Data communication in Silverlight 2.0 tutorial.
Share this article on   LinkedIn Google+

Petr Vozak

Product Owner responsible for Kentico E-commerce Solution. He writes about its new features, future plans and all related stuff you might be interested in.