如何在新地址下干净地重新启动WCF?

时间:2011-11-20 07:09:15

标签: c# wpf wcf

我有一个托管WCF服务的WPF C#应用程序。我有一个启动服务的例程,如果它已经存在则关闭它。 WebServce是ServiceHost类型的属性:

public void Start()
{
    try
    {

    var certificate = new X509Certificate2(certpath, "");

    String uri = "net.tcp://" + WCFAddress + "/MyService";
    Uri baseaddress = new Uri(uri);

    if (WebService != null) {
      try {
        WebService.Close();
      } catch (Exception) {
        WebService.Abort();
      }
    }

    WebService = new ServiceHost(MessageProvider, baseaddress);
    WebService.Credentials.ServiceCertificate.Certificate = certificate;
    WebService.Credentials.ClientCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;

    NetTcpBinding binding = new NetTcpBinding();
    binding.Security.Mode = SecurityMode.Message;
    binding.Security.Message.ClientCredentialType = MessageCredentialType.Certificate;
    binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.Certificate;
    WebService.AddServiceEndpoint(typeof(IMessageService), binding, baseaddress);

    WebService.Open();
    }
    catch (Exception e)
    {
        //exception handling
    }
}

这在启动时运行良好。如果我更改端口号(在WCFAddress中)并再次调用例程,它也可以正常工作。如果我更改主机上的地址并使用新的IP地址调用它,它也可以工作。但是,如果我将IP地址更改为无效IP地址,则服务将进入故障状态,并显示错误:

  

e = {“在侦听IP端点= 192.168.1.4:5000时发生TCP错误(10049:请求的地址在其上下文中无效)。”}

上面的Close()调用不会引发异常。

如果我然后将IP地址更改为正确的IP地址并再次调用,我会得到相同的错误,相同的旧的错误地址,即使我传递了正确的地址。此次,由于Faulted状态,Close()调用引发错误,导致Abort()调用。

我认为Abort()调用会允许重新创建服务吗?当我尝试使用新服务创建服务时,为什么它会给我一个关于旧地址的错误?它就像挂在旧的ServiceEndpoint上一样?

1 个答案:

答案 0 :(得分:1)

中止()。然后用新地址启动一个新实例..然后打开()。

相关问题