•
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:
- SilverLight.net forum post on making a WCF cross domain request
- Cross domain policy file helpers for Visual Studio - addes intellisense for the XML files
- Online cross domain policy file checker
- Silverlight cross domain web request example solution
- Example clientpolicy.xml file
- Example clientaccesspolicy.xml file
The code:
C#:
-
private void RequestButton_Click(object sender, RoutedEventArgs e)
-
{
-
try
-
{
-
// Create and being making the request/getting the response
-
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);
-
-
using (Stream responseStream = response.GetResponseStream())
-
{
-
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);
-
}
-
}
Leave a comment