Silverlight 2 Beta 2 呼叫 Web Services 相關問題

image 許多朋友在 Silverlight 2 中呼叫 Web Services 發生了 "The remote server returned an unexpected response: (404) Not Found." 的錯誤訊息,這個錯誤訊息可能的原因很多,其中最常發的因素就是 Web Services 所在的伺服器中,缺少了clientaccesspolicy.xml 這個安全管控的組態設定檔,Silverlight 2 為了防範安全相關的漏洞,預設是不允許 cross domain 呼叫 Web Services,預設僅允許呼叫下載網頁相同伺服器上的 Web Services,如果要 cross domain 呼叫 Web Services 就必須在 Web Services 所在伺服器上準備一個 clientaccesspolicy.xml 檔案,這個檔案若是找不到,Silverlight 2 便會自動嘗試是否能找到 Adobe Flash/Flex 所使用的 crossdomain.xml,若兩者都無法找到,便有可能出現 "The remote server returned an unexpected response: (404) Not Found."的錯誤訊息。

MSDN 網站中著 Silverlight 2 改版,一直將相關 clientaccesspolicy.xml 與 crossdomain.xml 的相關資料置於 https://msdn.microsoft.com/en-us/library/cc197955(VS.95).aspx,即便這個檔案有放置在正確地方,若是內容不正確,仍會出現 "The remote server returned an unexpected response: (404) Not Found."。一個權限最寬鬆的 Silverlight 2 Beta 2 clientaccesspolicy.xml  如下

<?xml version="1.0" encoding="utf-8"?>
<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>

由於錯誤訊息不精準,我建議發生此錯誤訊息的朋友,請下載安裝免費的 HTTP 監控工具 Fiddler,將有助於找出原因,若在 Fiddler 中看見取得 clientaccesspolicy.xml 就沒有後續動作,多半是 clientaccesspolicy.xml 內容不正確所造成的。由其在 Silverlight 2 Beta 1 與 Beta 2 間對於 clientaccesspolicy.xml 的處理有了些小改變,依據 Programming Silverlight 2 作者 Tim Heuer 的 blog 中描述, https://timheuer.com/blog/archive/2008/06/06/changes-to-accessing-services-in-silverlight-2-beta-2.aspx,Silverlight 2 Beta 2 的 clientaccesspolicy.xml 必須要有 http-request-headers 這個 XML 屬性,若缺少了這個屬性,就會出現 "The remote server returned an unexpected response: (404) Not Found.",倘若您的程式 cross domain 呼叫 Web Services 在 Beta 1 時候運作正常,但到了 Beta 2 就會發生錯誤,不妨檢查一下是否缺了 http-request-headers 這個 XML 屬性。