silverlight訪問WebService遭遇跨域問題

嘗試向 URI「http://localhost:8001/AccountService.svc」發出請求時出錯。這多是因爲試圖以跨域方式訪問服務而又沒有正確的跨域策略,或策略不適用於 SOAP 服務。您可能須要與該服務的全部者聯繫,以發佈跨域策略文件並確保該文件容許發送 SOAP 相關的 HTTP 標頭。出現此錯誤也多是因爲使用的是 Web 服務代理中的內部類型而沒有使用 InternalsVisibleToAttribute 屬性。有關詳細信息,請參閱內部異常。 web

解決方法:跨域

1、在WCF項目根目錄下添加clientaccesspolicy.xml文件dom

 


<?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>

2、在silverlight項目中添加一箇中介類ServerManager.cside

 


public class ServerManager
    {
        
private static ServiceWcfClient servicePicture = new ServiceWcfClient();

        
internal static ServiceWcfClient GetPox()
        {
            
if (servicePicture.State == System.ServiceModel.CommunicationState.Created)
            {
                servicePicture.Endpoint.Address 
= new System.ServiceModel.EndpointAddress("http://localhost:52207/ServiceWcf.svc");
                
return servicePicture;
            }
            
else
            {
                
return servicePicture;
            }
        }
    }

3、實例化實體類的時候通常是這樣:ServiceWcfClient clientWcf = new ServiceWcfClient();spa

換成:ServiceWcfClient clientWcf = ServerManager.GetPox();代理

PS:下面是原創內容了code

事實證實,僅僅添加一項clientaccesspolicy.xml是不夠的,還要配置一下WCF下面的web.config文件,添加services節點,下面貼代碼:orm

<services>xml

      <service behaviorConfiguration="WcfService1.Service1Behavior" name="WcfService1.Service1">blog

        <endpoint binding="basicHttpBinding" bindingConfiguration="" contract="WcfService1.IService1" >

          <identity>

            <dns value="localhost"/>

          </identity>

        </endpoint>

      </service>

    </services>

相關文章
相關標籤/搜索