WCF - 地址过滤器不匹配

WCF - AddressFilter mismatch

我有一个自托管的 WCF 服务,调用它时出现以下异常:

The message with To 'net.tcp://localhost:53724/Test1' cannot be processed at the receiver, due to an AddressFilter mismatch at the EndpointDispatcher. Check that the sender and receiver's EndpointAddresses agree.

有效的解决方案是在服务接口实现 class 之前添加 [ServiceBehavior(AddressFilterMode = AddressFilterMode.Prefix)]。但事实并非如此!所以,我试图找出错误的根源以将其删除。

我发现 当我添加 ServiceBehavior 属性并且调用成功时 - 以下内容:OperationContext.Current.EndpointDispatcher.EndpointAddress Returns: net.tcp://localhost/Test1 - 注意没有端口。这实际上就是我提供 ServiceHost.Open 方法的内容。但是添加了端口,因为我指定了 ListenUriMode.Unique .

所以:如何修复 AddressFilterMode.Exact 的错误?

重现代码:

[ServiceContract]
public interface IWCF1
{
    [OperationContract]
    bool SendMessage(string message);
}

[ServiceBehavior(AddressFilterMode = AddressFilterMode.Prefix)]
public class WCF1 : IWCF1
{
    public bool SendMessage(string message)
    {
        Debug.WriteLine("Message: " + message);
        Debug.WriteLine(OperationContext.Current.EndpointDispatcher.EndpointAddress, "EndpointAddress");//Does not include the port!
        return true;
    }
}


public void test()
{
    Uri uri2 = Service(typeof(WCF1), typeof(IWCF1), "Test1");
    IWCF1 iwcf1 = CreateChannel(uri2.ToString());
    new Task(() => iwcf1.SendMessage("abc")).Start();
}

public Uri Service(Type class1, Type interface1, string uri)
{
    string serviceUri = "net.tcp://localhost/" + uri;
    ServiceHost host = new ServiceHost(class1, new Uri(serviceUri));
    ServiceEndpoint ep = host.AddServiceEndpoint(interface1, new NetTcpBinding(SecurityMode.None), serviceUri);
    ep.ListenUriMode = ListenUriMode.Unique;
    host.Open();
    return host.ChannelDispatchers[0].Listener.Uri;
}

public static IWCF1 CreateChannel(string address)
{
    EndpointAddress ep = new EndpointAddress(address);
    ChannelFactory<IWCF1> channelFactory = new ChannelFactory<IWCF1>(new NetTcpBinding(SecurityMode.None), ep);
    return channelFactory.CreateChannel();
}

我怀疑AddressFilterMode.Exact错误的来源涉及逻辑端点和物理服务地址之间的差异。

EndpointAddress是一个服务的逻辑地址,也就是SOAP消息的寻址地址。 ListenUri 是服务的物理地址。它具有服务端点实际侦听当前机器上的消息的端口和地址信息。逻辑端点地址,而不是物理服务位置,被调度程序用于匹配和过滤,因此精确匹配找不到服务的原因。

物理地址与逻辑地址不同:

  net.tcp://localhost:53724/Test1  !=  net.tcp://localhost/Test1  

需要考虑的几个选项:
继续使用AddressFilterMode.Prefix
尝试指定 HostNameComparisonMode
提前指定端口

参考资料: https://msdn.microsoft.com/en-us/library/aa395210%28v=vs.110%29.aspx https://msdn.microsoft.com/en-us/magazine/cc163412.aspx#S4