當Silverlight同時遇上TCP和HTTP的WCF服務
如果只是單一的TCP通信
如果你的silverlight應用因為一些特殊原因跟WCF通信時使用的不是Http協議,而是TCP協議,并且是Host到控制臺上的。那么假設是下面這個簡單的服務:
1,WCF中的主機服務代碼如下:
{
static void Main(string[] args)
{
ServiceHost host = new ServiceHost(typeof(HelloService));
host.Open();
Console.WriteLine("服t務?已?經-啟?動ˉ!?");
}
}
[ServiceContract]
interface IHelloService
{
[OperationContract]
string SayHello(string name);
}
public class HelloService : IHelloService
{
public string SayHello(string name)
{
return "hello," + name;
}
}
<bindings>
<netTcpBinding>
<binding name="netTcpBindConfig">
<security mode="None"/>
</binding>
</netTcpBinding>
</bindings>
<services>
<service name="HelloService">
<host>
<baseAddresses>
<add baseAddress="net.tcp://localhost:4503/HelloService"/>
</baseAddresses>
</host>
<endpoint address="" binding="netTcpBinding" contract="WCF.IHelloService"></endpoint>
<endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange" ></endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="WCF.HelloServiceBehavior">
<serviceMetadata/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
</configuration>
3,鑒于silverlight4在訪問服務的時候會請求主機的80端口得到一個策略文件,如果你按照這個要求在wwwroot下放置這么個xml的策略文件:
<access-policy>
<cross-domain-access>
<policy>
<allow-from http-request-headers="*">
<domain uri="*" />
</allow-from>
<grant-to>
<socket-resource port="4502-4534" protocol="tcp" />
</grant-to>
</policy>
</cross-domain-access>
</access-policy>
那這個服務就OK了。可以正常提供服務了。
如果需要加載另外的DLL,且這DLL訪問http的WCF服務呢?
也許您在VS2010中調試會OK,但是在部署到服務器上后,打開頁面會發現一個錯誤,提示的居然是安全性錯誤。會是什么原因呢,我百思不得其解,奇怪的地方就在于,為什么在VS2010中調試加載的DLL可以正常訪問服務,但是一發布就訪問不到了呢。后來,在同事的提醒下,我在wwwroot下的文件clientaccesspolicy.xml中加了一行配置:
全部配置為:
<access-policy>
<cross-domain-access>
<policy>
<allow-from http-request-headers="*">
<domain uri="*" />
</allow-from>
<grant-to>
<socket-resource port="4502-4534" protocol="tcp" />
<resource path="/" include-subpaths="true"/>
</grant-to>
</policy>
</cross-domain-access>
</access-policy>
再打開頁面,通過!
補充:由于silverlight在訪問WCF服務時,需要在80端口獲取一個策略文件,而這個策略文件便是給了silverlight一個訪問主機的權限。由于我們的silverlight應用本身是訪問TCP協議的WCF的,所以需要在wwwroot下放一個策略文件允許TCP的訪問,但是由于silverlight應用中又加載了一個DLL,這個DLL是訪問HTTP協議的WCF的,所以在請求TCP授權的同時,需要獲得HTTP的授權,而<resource path="/" include-subpaths="true"/> 這個配置節正是滿足了訪問IIS根目錄及子目錄的權限,當然,包括WCF服務在內。