【问题标题】:WCF client cannot connect to service with dynamic portWCF 客户端无法使用动态端口连接到服务
【发布时间】:2016-11-07 13:40:21
【问题描述】:

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

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

当我将“0”作为端口号传递时,WCF 服务会动态获取一个可用端口。

虽然客户端获取端口并将该端口传递给服务器,但连接始终以“EndpointNotFoundException”和“地址过滤器不匹配”结束。

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

//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;

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

【问题讨论】:

    标签: c# .net wcf


    【解决方案1】:

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

    基本代码:

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

    【讨论】:

    • 非常感谢,帮了大忙!
    猜你喜欢
    • 1970-01-01
    • 2013-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-15
    • 1970-01-01
    相关资源
    最近更新 更多