从ServiceHost获取端口号

时间:2014-06-12 19:19:26

标签: c# .net wcf tcp port

我正在使用端口0创建WCF ServiceHost以获取动态分配的端口:

ServiceHost host = new ServiceHost(typeof(MyClass), new Uri("net.tcp://localhost:0/abc"));
host.AddServiceEndpoint(typeof(MyInterface), new NetTcpBinding(SecurityMode.None), "net.tcp://localhost:0/abc");

如何分配端口号?

我试过了:

host.ChannelDispatchers[0].Listener.Uri.Port

但它只返回0,这可能是错误的。

1 个答案:

答案 0 :(得分:4)

好吧,我想我弄明白了。您需要确保将listen URI行为设置为unique并将其打开。默认情况下,它设置为显式。

我制作了一个包含以下服务合同的虚假服务类:

[ServiceContract]
public class MyClass
{
   [OperationContract]
   public string Test()
   {
      return "test";
   }
}

并添加了相应的测试类:

[TestClass]
public class TestMyClass
{
    [TestMethod]
    public string TestPortIsNotZero(){
        var host = new ServiceHost(typeof(MyClass), 
            new Uri("net.tcp://localhost:0/abc"));
        var endpoint = host.AddServiceEndpoint(typeof(MyClass), 
            new NetTcpBinding(SecurityMode.None), "net.tcp://localhost:0/abc");
        //had to set the listen uri behavior to unique
        endpoint.ListenUriMode = ListenUriMode.Unique;
        //in addition open the host
        host.Open();

        foreach (var cd in host.ChannelDispatchers)
        {
           //prints out the port number in the dynamic range
           Debug.WriteLine(cd.Listener.Uri.Port);
           Assert.IsTrue(cd.Listener.Uri.Port >= 0); 
        }
   }
}