我遇到了一个问题。我对WCF还不太熟悉,希望能得到帮助。
以下是我的代码:
public static void StartHosts()
{
try
{
// Create a new host
ServiceHost host = new ServiceHost(typeof(ServerTasks));
List<IPAddress> ips = new List<IPAddress>(Dns.GetHostAddresses(Dns.GetHostName()));
if (IPAddress.Loopback != null)
ips.Add(IPAddress.Loopback);
ips.RemoveAll(i => i.AddressFamily != AddressFamily.InterNetwork);
foreach (var ip in ips)
{
string uri = string.Empty;
// Formulate the uri for this host
uri = string.Format(
"net.tcp://{0}:{1}/ServerTasks",
ip.ToString(),
ServerSettings.Instance.TCPListeningPort
);
// Add the endpoint binding
host.AddServiceEndpoint(
typeof(ServerTasks),
new NetTcpBinding(SecurityMode.Transport) { TransferMode = TransferMode.Streamed },
uri
);
}
// Add the meta data publishing
var smb = host.Description.Behaviors.Find<ServiceMetadataBehavior>();
if (smb == null)
smb = new ServiceMetadataBehavior();
smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
host.Description.Behaviors.Add(smb);
host.AddServiceEndpoint(
ServiceMetadataBehavior.MexContractName,
MetadataExchangeBindings.CreateMexTcpBinding(),
"net.tcp://localhost/ServerTasks/mex"
);
// Run the host
host.Open();
}
catch (Exception exc)
{
DebugLogger.WriteException(exc);
}
}
在代码的“host.Open();”这一行抛出了异常。
异常信息如下: System.InvalidOperationException A registration already exists for URI 'net.tcp://192.168.1.45:4329/ServerTasks'。 我的目标是将服务绑定到机器上的所有网络地址,以便客户端应用程序可以从它们看到的任何网络中访问该服务。运行此代码时,它会查找并尝试设置约5个不同IP的绑定,包括127.0.0.1。
192.168.1.45是它尝试绑定的第二个IP。在它抛出异常的那一点上,我可以通过使用netstat看到该程序已经将第一个IP绑定到端口4329上。在异常中提到的地址上没有任何东西绑定到端口4329。
注意:我已经尝试在foreach循环内创建的NetTcpBinding的PortSharingEnabled属性设置为true,但我仍然遇到了相同的错误。
如果有需要更多信息,请随时联系我。
谢谢!