Despite being considerably more work, because you will have to parse the results yourself, another means of communicating with a server is through the use of standard HTTP requests. For example, you might wish to download an XML file from the server, or even consume RESTful services (a.k.a. WebHTTP services). You will also use HTTP requests to download files from a server (such as images).
There are two ways to make HTTP requests in Silverlight. Silverlight has both a WebClient
and a WebRequest
class that you can use for uploading and downloading data over HTTP to/from the server. WebRequest
gives you finer control over the request; however, WebClient
is the easiest to use for simple HTTP download tasks. It provides two means of downloading data (DownloadString
and OpenRead
), and two means of uploading data (UploadString
and OpenWrite
). DownloadString
/UploadString
simply downloads/uploads the data as a string, making communicating plain text easy, and OpenRead
/OpenWrite
uses a stream (best for binary data). For example, the following is all it takes to download a text file from the server and load the contents into a string variable:
private void StartDownload(string url)
{
WebClient client = new WebClient();
client.DownloadStringCompleted += client_DownloadStringCompleted;
client.DownloadStringAsync(new Uri(url));
}
private void client_DownloadStringCompleted(object sender,
DownloadStringCompletedEventArgs e)
{
string result = e.Result;
// Do something with the result
}
By default, Silverlight uses the browser's networking stack, when running inside the browser, which places some limits on what you can do when making HTTP requests from Silverlight. Limitations that the browser's networking stack imposes include the following:
To support out-of-browser (OOB) mode, the client networking stack was introduced in Silverlight 3, but you can also invoke this networking stack instead, while running inside the browser, to work around these limitations of the browser's networking stack.
Note There are some downsides of using the client networking stack, such as the lack of content caching and authentication support.
To use the client networking stack, simply call the RegisterPrefix
method on the WebRequest
(or HttpWebRequest
) class, passing in a prefix (which can be the scheme, or even a domain) to which future calls will use the given networking stack, and passing in the networking stack that those calls will use, with ClientHttp
representing the client networking stack, like so:
WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);