WebClient.DownloadStringAsync在Silverlight中抛出安全exception

第一次使用Silverlight! 在线教程之后。 我正在创建一个应用程序,允许用户使用WebClient从Digg网站搜索故事,并将它们显示在Silverlight控件的数据网格中。

这是代码:

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); } } 

每当我在diggService_DownloadStringCompleted事件处理程序上设置diggService_DownloadStringCompleted并单击搜索按钮时, e.Error始终等于没有消息的System.Security.SecurityException和具有“安全错误”消息的相同类型的内部exception。 堆栈跟踪是:

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

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

在System.Net.WebClient.GetWebResponse(WebRequest请求,IAsyncResult结果)

在System.Net.WebClient.DownloadBitsResponseCallback(IAsyncResult结果)

经过一些沉重的谷歌搜索后,我看到人们提到了一个crossdomain.xml文件。 不完全确定这是什么,但我在运行Silverlight控件的Web服务器的根目录中添加了一个,并添加了以下文本。 没有任何区别:

     

这是怎么回事?

需要将crossdomain.xml文件放在您尝试从中下载文件的服务器上,而不是放在为Silverlight应用程序提供服务的服务器上。

如果服务器没有crossdomain.xml文件,则Silverlight运行时不允许应用程序从该服务器下载数据。 默认情况下,它只能访问从中下载的服务器(相同的原始策略)。

Digg.com没有跨域文件(意味着Silverlight和Flash客户端无法直接使用API​​)。 无法直接从Silverlight访问。

一种解决方法是在您的Web主机上创建代理。 代理将从您的Web服务器调用Digg的API,而不是直接从Silverlight客户端调用。

Silverlight ==> YourWebHost ==> Digg.com

另一种解决方法是使用他们的JavaScript API,然后使用JavaScript桥从Silverlight与JavaScript通信。

Silverlight ==> JavaScript ==> Digg.Com ==> JavaScript ==> Silverlight

对于JavaScript调用: http : //developers.digg.com/response

Silverlight桥参考: http : //msdn.microsoft.com/en-us/library/cc645076( VS.95) .aspx演练:Silverlight到JavaScript: http : //msdn.microsoft.com/en-us/library/ cc221359(v = VS.95).aspx JavaScript to Silverlight: http : //msdn.microsoft.com/en-us/library/cc221414 (v = VS.95).aspx