我有一个自托管的 WCF 服务,在调用它时遇到以下异常:
由于 EndpointDispatcher 上的 AddressFilter 不匹配,无法在接收方处理带有 To 'net.tcp://localhost:53724/Test1' 的消息。检查发送方和接收方的 EndpointAddresses 是否一致。
[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();
}
Run Code Online (Sandbox Code Playgroud)
我怀疑错误的根源AddressFilterMode.Exact涉及逻辑端点和物理服务地址之间的差异。
是EndpointAddress服务的逻辑地址,即 SOAP 消息寻址到的地址。这ListenUri是服务的物理地址。它具有服务端点实际侦听当前计算机上的消息的端口和地址信息。调度程序使用逻辑端点地址(而不是物理服务位置)进行匹配和过滤,这就是精确匹配找不到服务的原因。
物理地址与逻辑地址不同:
net.tcp://localhost:53724/Test1 != net.tcp://localhost/Test1
Run Code Online (Sandbox Code Playgroud)
需要考虑的几个选项:
继续使用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