2008-10-31 68 views
13

我想讓Silverlight與快速示例應用程序一起工作,並在另一臺計算機上調用休息服務。具有其他服務的服務器有一個clientaccesspolicy.xml它看起來像:Silverlight休息服務,安全異常

<access-policy> 
    <cross-domain-access> 
     <policy> 
      <allow-from http-request-headers="*"> 
       <domain uri="*"/> 
      </allow-from> 
      <grant-to> 
       <resource path="/" include-subpaths="true"/> 
      </grant-to> 
     </policy> 
    </cross-domain-access> 
</access-policy> 

,並正在回升(至少根據我所遇到的網絡痕跡),並且對於跨域沒有要求。 XML。在C#代碼如下所示:

public Page() 
{ 
    InitializeComponent(); 

    string restUrl = "http://example.com/rest_service.html?action=test_result"; 

    WebClient testService = new WebClient(); 
    testService.DownloadStringCompleted += new DownloadStringCompletedEventHandler(testService_DownloadStringCompleted); 
    testService.DownloadStringAsync(new Uri(restUrl, UriKind.Absolute)); 

} 

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

不過,我總是得到以下安全錯誤回:

 
{System.Security.SecurityException ---> System.Security.SecurityException: Security error. 
    at System.Net.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult) 
    at System.Net.BrowserHttpWebRequest.c__DisplayClass5.b__4(Object sendState) 
    at System.Net.AsyncHelper.c__DisplayClass2.b__0(Object sendState) 
    --- End of inner exception stack trace --- 
    at System.Net.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state) 
    at System.Net.BrowserHttpWebRequest.EndGetResponse(IAsyncResult asyncResult) 
    at System.Net.WebClient.GetWebResponse(WebRequest request, IAsyncResult result) 
    at System.Net.WebClient.DownloadBitsResponseCallback(IAsyncResult result)} 

我在做什麼錯?爲什麼安全錯誤告訴我一些更有用的信息?

+1

你不得不改變它的工作? – stimms 2009-04-19 23:55:35

+0

當您的Silverlight項目不是Web項目時,您無法調用休息服務。 – 2009-04-20 15:16:50

回答

8

如果您還沒有這樣做,我會先嚐試將restUrl更改爲更簡單,如同一個服務器上的靜態HTML頁面(或者如果需要在您自己的服務器上),以驗證您的主代碼是否有效。

假設安全例外特定於該REST URL(或站點),您可以查看URL Access Restrictions in Silverlight 2文章。除了更爲人熟知的跨域規則之外,還有一些涉及文件類型和「互聯網區域」的非顯而易見的安全規則。

我第二次抱怨Silverlight中的許多異常消息不是很有幫助。上面引用的MSDN文章包含一個有趣的筆記:

當用戶得到由違反這些訪問策略之一導致的錯誤時,該錯誤可能不會指示確切的原因。

+0

啊,這個鮮爲人知的跨區域限制......花了我好幾天的時間才發現這是我的問題。感謝您的鏈接。 +1 – Phil 2011-11-17 15:35:59

0

從「可信網站」加載HTML網頁失敗,我的本地應用程序(http://localhost/) - 直到我說本地主機到受信任站點列表。 Silverlight可以防止「跨區域」調用(在本例中是Local Network vs. Trusted Sites)和「cross scheme」調用(例如http vs https)。

到目前爲止,它僅適用於「crossdomain.xml」文件。我首先嚐試了「clientaccesspolicy.xml」,但沒有得到它。

4

我無法進行跨域REST HTTP刪除,而無需向clientaccesspolicy.xml中的allow-from元素添加http-methods =「*」。當我添加http-methods屬性時,一切正常,SecurityException停止。