在WCF中,每个终结点都包含两个不同的地址——逻辑地址和物理地址。逻辑地址就是终结点Address属性表示的地址。至于物理地址,对于消息发送放来讲,就是消息被真正发送的目的地址;而对于消息的接收放来讲,就是监听器真正监听的地址。
1、服务端的物理地址
在默认的情况下,终结点的逻辑地址和物理地址是同一个URI。换句话说,终结的逻辑地址是必须的,如何物理地址没有指定的,默认使用逻辑地址作为物理地址。对于消息接收方的终结点来讲,物理地址就是监听地址,通过ServiceEndpoint的ListenUri表示:
//---------------------------------------------------------------
// EndpointAddress & WCF Addressing (c) by 2008 Jiang Jin Nan
//---------------------------------------------------------------
public class ServiceEndpoint
{
... ...
public Uri ListenUri { get; set; }
}
在对服务进行寄宿的时候,我们可以调用SeriviceHostBase或者ServiceHost的AddServiceEndpoint对应的重载来为添加的终结点指定ListenUri:
//---------------------------------------------------------------
// EndpointAddress & WCF Addressing (c) by 2008 Jiang Jin Nan
//---------------------------------------------------------------
public abstract class ServiceHostBase : CommunicationObject, IExtensibleObject<ServiceHostBase>, IDisposable
{
... ...
public ServiceEndpoint AddServiceEndpoint(string implementedContract, Binding binding, string address, Uri listenUri);
public ServiceEndpoint AddServiceEndpoint(string implementedContract, Binding binding, Uri address, Uri listenUri);
}
public class ServiceHost : ServiceHostBase
{
... ...
public ServiceEndpoint AddServiceEndpoint(Type implementedContract, Binding binding, string address, Uri listenUri);
public ServiceEndpoint AddServiceEndpoint(Type implementedContract, Binding binding, Uri address, Uri listenUri);
}
在下面的代码片断中,就为终结点指定了一个同于逻辑地址的物理地址(ListenUri):
//---------------------------------------------------------------
// ListenUri.cs (c) by 2008 Jiang Jin Nan
//---------------------------------------------------------------
using (ServiceHost serviceHost = new ServiceHost(typeof(CalculateService)))
{
serviceHost.AddServiceEndpoint(typeof(ICalculate),new WSHttpBinding(),
"http://127.0.0.1:9999/calculateservice",
new Uri ("http://127.0.0.1:8888/calculateservice"));
Console.Read();
}
当然,ListenUri也可以通过配置进行指定,下面的配置和上面的代码是等效的:
<configuration>
<system.serviceModel>
<services>
<service name="Artech.WcfServices.Services.CalculateService">
<endpoint binding="wsHttpBinding"
contract="Artech.WcfServices.Contracts.ICalculate" address="http://127.0.0.1:8888/calculateservice"
listenUri="http://127.0.0.1:8888/calculateservice" />
</service>
</services>
</system.serviceModel>
</configuration>