當Silverlight同時遇上TCP和HTTP的WCF服務

作者: Leon Weng  來源: 博客園  發布時間: 2010-10-02 19:56  閱讀: 4080 次  推薦: 0   原文鏈接   [收藏]  

  如果只是單一的TCP通信

  如果你的silverlight應用因為一些特殊原因跟WCF通信時使用的不是Http協議,而是TCP協議,并且是Host到控制臺上的。那么假設是下面這個簡單的服務:

image

  1,WCF中的主機服務代碼如下:

 
class Program
{

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;
}
}
  2,app.config可以簡單配置成這樣:
 
<configuration>
<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的策略文件:

 
<?xml version="1.0" encoding="utf-8"?>
<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中加了一行配置:

 
<resource path="/" include-subpaths="true"/>

  全部配置為:

 
<?xml version="1.0" encoding="utf-8"?>
<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服務在內。

0
0
 
 
 

文章列表

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()