How to make a cross domain web request with SilverLight 2

24 Oct 2008

To make a cross domain web request with SilverLight 2 really isn't that tough. I did have some problems with RC0 but I have no idea why. I just tried writing a little app to do this and it worked straight away.

Here's the code. It's obviously part of a full solution containing a Web Application and a SilverLight Application project. I've also uploaded it.

Useful Information:

  • You can not do a cross domain request over HTTPS.
  • You can do a cross domain request over HTTP.
  • To be able to make the cross domain request the server that you are making the request to needs to have either (requires clarification)  crossdomain.xml and/or clientaccesspolicy.xml in the root of the webserver.

Resources/links:

The code:

[csharp]
private void RequestButton_Click(object sender, RoutedEventArgs e)
{
try
{
// Create and being making the request/getting the response
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri("https://www.leggetter.co.uk/"));
request.BeginGetResponse(HandleResponse, request);
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}

private void HandleResponse(IAsyncResult result)
{
try
{
// Finish getting the response and then read the response in chunks
HttpWebRequest request = (HttpWebRequest)result.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);

StringBuilder readText = new StringBuilder();
using (Stream responseStream = response.GetResponseStream())
{
byte[] buffer = new byte[1024];
int read = responseStream.Read(buffer, 0, buffer.Length);
while (read > 0)
{
readText.Append(Encoding.UTF8.GetString(buffer, 0, read));
read = responseStream.Read(buffer, 0, buffer.Length);
}
}

// Display the response text
Dispatcher.BeginInvoke(delegate()
{
ResponseText.Text = readText.ToString();
});
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
[/csharp]