从 ServiceHost 获取端口号

isp*_*iro 1 .net c# port wcf tcp

我正在创建一个ServiceHost带有端口 0的 WCF以获得动态分配的端口:

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");
Run Code Online (Sandbox Code Playgroud)

如何获得分配的端口号?

我试过:

host.ChannelDispatchers[0].Listener.Uri.Port
Run Code Online (Sandbox Code Playgroud)

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

wbe*_*ett 5

好吧,我想我想通了。您需要确保将侦听 URI 行为设置为唯一并打开它。默认情况下,它设置为显式。

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

[ServiceContract]
public class MyClass
{
   [OperationContract]
   public string Test()
   {
      return "test";
   }
}
Run Code Online (Sandbox Code Playgroud)

并添加了相应的测试类:

[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); 
        }
   }
}
Run Code Online (Sandbox Code Playgroud)