C# – WebClient.DownloadStringAsync throwing Security Exception in Silverlight

csilverlightwebclient

First time using Silverlight ever! Following an online tutorial. I'm creating an app which allows the user to search for stories from the Digg website using a WebClient and displays them in a data grid in a Silverlight control.

Here's the code:

private void btnSearch_Click(object sender, RoutedEventArgs e)
{
    string topic = txtTopic.Text;

    string diggUrl = String.Format("http://services.digg.com/stories/topic/{0}?count=20&appkey=http%3A%2F%2Fscottgu.com", topic);

    WebClient diggService = new WebClient();
    diggService.DownloadStringCompleted += new DownloadStringCompletedEventHandler(diggService_DownloadStringCompleted);
    diggService.DownloadStringAsync(new Uri(diggUrl));
}

void diggService_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    if (e.Error == null)
    {
        DisplayStories(e.Result);
    }
}

Whenever I put a break point on the diggService_DownloadStringCompleted event handler and click the search button e.Error always equals a System.Security.SecurityException with no message and an inner exception of the same type with a message of 'Security error.'. The stack trace is:

at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)

at System.Net.Browser.BrowserHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)

at System.Net.WebClient.GetWebResponse(WebRequest request, IAsyncResult result)

at System.Net.WebClient.DownloadBitsResponseCallback(IAsyncResult result)

After some heavy googling I've seen people mention a crossdomain.xml file. Not entirely sure what this is but I added one to root directory of the web server running the Silverlight control any and added the following text. didn't make any difference:

<?xml version="1.0" ?>
<cross-domain-policy>
  <allow-access-from domain="*" />
</cross-domain-policy>

What's going on?

Best Answer

The crossdomain.xml file needs to be placed on the server you're trying to download the file from, not on the server that serves the Silverlight application.

If the server doesn't have a crossdomain.xml file, the Silverlight runtime does not allow your application to download data from that server. By default, it can only access the server it was downloaded from (same origin policy).

Related Topic