c# – WCF – AddressFilter不匹配

我有一个自托管的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.

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

我发现了
当我添加ServiceBehavior属性并且调用成功时 – 以下内容:OperationContext.Current.EndpointDispatcher.EndpointAddress
返回: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

点赞