WCF客户端无法使用动态端口连接到服务

时间:2016-11-07 13:40:21

标签: c# .net wcf

我有2个应用程序,一个使用WCF服务,另一个使用WCF客户端。

当我使用静态端口时,它们之间的连接正常。

当我传递“0”作为端口号时,WCF服务动态获得可用端口。

虽然客户端获取端口并将该端口传递给服务器,但连接始终以“EndpointNotFoundException”和“Address Filter Mismatch”结束。

我评论了“MetaData”绑定,因为它没有帮助。

//IP address is determined by code, for simplicity in this example it is hardcoded
//set port to 0 to get a free port 
var url = $"net.tcp://190.150.140.22:0/UiHost";
var UiHost = new ServiceHost(typeof(ShippingUIService), new Uri(url));

//var mBehave = new ServiceMetadataBehavior();
//UiHost.Description.Behaviors.Add(mBehave);

var ntb = new NetTcpBinding(SecurityMode.None) { ListenBacklog = 10, MaxConnections = 20, PortSharingEnabled = false };

var endPoint = UiHost.AddServiceEndpoint(typeof(Core.IShippingUIService), ntb, "");
//UiHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding(), "mex");
// Tell WCF to actually bind to a free port instead of 0
endPoint.ListenUriMode = System.ServiceModel.Description.ListenUriMode.Unique;

UiHost.Open();

//Uri is saved, so the client can access the service
var serviceHostUri = UiHost.ChannelDispatchers.First().Listener.Uri.AbsoluteUri;
log.Info($"UI Service started. With address {serviceHostUri}");

这段代码是否有可能不返回给定的实际端口号?

UiHost.ChannelDispatchers.First()Listener.Uri.AbsoluteUri;

提前感谢您的每一个提示。

1 个答案:

答案 0 :(得分:0)

您的服务主机的默认地址过滤器是在不知道动态分配的端口的情况下生成的,因此不匹配。最简单的解决方案可能是使用AddressFilterMode = AddressFilterMode.Any将您的服务类型(ShippingUIService)设置为响应任何地址。

代码的基本部分:

[ServiceBehavior(AddressFilterMode = AddressFilterMode.Any)]
class ShippingUIService {
  // Class members
}