Phil Leggetter - Software Consultant » Page 'How to make a cross domain web request with SilverLight 2'

How to make a cross domain web request with SilverLight 2

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:

C#:
  1. private void RequestButton_Click(object sender, RoutedEventArgs e)
  2. {
  3.     try
  4.     {
  5.         // Create and being making the request/getting the response
  6.         HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri("http://www.leggetter.co.uk/"));
  7.         request.BeginGetResponse(HandleResponse, request);
  8.     }
  9.     catch (Exception ex)
  10.     {
  11.         Debug.WriteLine(ex);
  12.     }
  13. }
  14.  
  15. private void HandleResponse(IAsyncResult result)
  16. {
  17.     try
  18.     {
  19.         // Finish getting the response and then read the response in chunks
  20.         HttpWebRequest request = (HttpWebRequest)result.AsyncState;
  21.         HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
  22.  
  23.         StringBuilder readText = new StringBuilder();
  24.         using (Stream responseStream = response.GetResponseStream())
  25.         {
  26.             byte[] buffer = new byte[1024];
  27.             int read = responseStream.Read(buffer, 0, buffer.Length);
  28.             while (read> 0)
  29.             {
  30.                 readText.Append(Encoding.UTF8.GetString(buffer, 0, read));
  31.                 read = responseStream.Read(buffer, 0, buffer.Length);
  32.             }
  33.         }
  34.  
  35.         // Display the response text
  36.         Dispatcher.BeginInvoke(delegate()
  37.         {
  38.             ResponseText.Text = readText.ToString();
  39.         });
  40.     }
  41.     catch (Exception ex)
  42.     {
  43.         Debug.WriteLine(ex);
  44.     }
  45. }

Leave a comment

XHTML - You can use:<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

© 2008 Phil Leggetter - Software Consultant is powered by WordPress