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.
class and HttpWebRequest
class in our demo application will request data from the same HTTP-based service. Please, follow these steps to create it:
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:
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:
Now you are ready to consume data of the service by WebClient
classes. Bellow you can find their implementation in our demo application.
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:
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:
This article is part of the Data communication in Silverlight 2.0