每一個 WCF 服務都會關係到地址(Address)、綁定(Binding)和契約(Contract),而 WCF 則通過 Endpoint 將 ABC 三個方面聯繫在一起。每一個 Endpoint 都必須包括 ABC 三個方面,缺一不可,而 host 進程會提供 Endpoint 供客戶端調用。每個 Endpoint 都對應一個唯一地址,但是多個 Endpoint 可以共享相同的綁定和契約,每個服務又可以提供多個 Endpoint 供客戶端掉用。
使用配置文件
再次體現 Microsoft 的傻瓜式編程。唯一值得注意的地方是在 service 節點中添加了 behaviorConfiguration 屬性。
< configuration xmlns ="http://schemas.microsoft.com/.NetConfiguration/v2.0" >
< system .serviceModel >
< services >
<!-- <service name="MyService" behaviorConfiguration="returnFaults">
<endpoint contract="IMyService" binding="wsHttpBinding"/>
</service> -->
< service name ="Anrs.Service.AnrsService" behaviorConfiguration ="returnFaults" >
< endpoint contract = "Anrs.Service.IAnrsServiceContract1"
binding = "wsHttpBinding"
address = "http://localhost:4021/AnrsServiceByIIS/AnrsService/" />
</ service >
</ services >
< behaviors >
< serviceBehaviors >
< behavior name ="returnFaults" >
< serviceMetadata httpGetEnabled ="true" ></ serviceMetadata >
< serviceDebug includeExceptionDetailInFaults ="true" />
</ behavior >
</ serviceBehaviors >
</ behaviors >
</ system.serviceModel >
< system .web >
< compilation debug ="true" />
</ system.web >
</ configuration >
使用配置文件的好處自不待言,無論是修改了服務的地址、綁定還是契約,都不需要重新編譯甚至部署。配置完成後,就能在瀏覽器中看到如下的畫面了。
編程控制 Endpoint
相對於配置文件的簡單,編程控制 Endpoint 也不會多幾行代碼。下面的代碼就相當於上面的配置文檔。
using System.ServiceModel;
using System.ServiceModel.Channels;
namespace Anrs.Service
{
class Program
{
static void Main( string [] args)
{
ServiceHost sh = new ServiceHost( typeof (AnrsService));
Binding wsHttpBinding = new WSHttpBinding();
sh.AddServiceEndpoint( typeof (IAnrsServiceContract1),
wsHttpBinding,
new Uri( " http://localhost:8086/AnrsService/ " ));
sh.Open();
Console.Write( " Press any key to exit " );
Console.ReadLine();
sh.Close();
}
}
}