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:

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("http://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);
    }
}

Related posts:

  1. Using Fiddler to trick Silverlight into allowing a crossdomain Web Request
  2. Using Fiddler to help develop cross domain capable JavaScript web applications
  3. Silverlight uses XCP tmp files for Web Requests
  4. Making cross domain JavaScript requests using XMLHttpRequest or XDomainRequest
  5. Response.Redirect in Windows Azure
Tagged with:
 
Set your Twitter account name in your settings to use the TwitterBar Section.