【问题标题】:Why isn't the WCF service getting called from the changed address?为什么没有从更改的地址调用 WCF 服务?
【发布时间】:2014-08-10 17:48:55
【问题描述】:

我尝试动态更改 app.config 文件的终点地址。在我打印地址时更改后,我得到更改后的地址。但是该服务似乎没有使用该地址。即使我输入了错误的地址,它似乎也可以工作。似乎它正在使用默认地址。请帮忙。我的代码如下:

 static void UpdateAppConfig(String Name)
    {
        var doc = new XmlDocument();
        doc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
        XmlNodeList endpoints = doc.GetElementsByTagName("endpoint");
        foreach (XmlNode item in endpoints)
        {
            var addressAttribute = item.Attributes["address"];
            if (!ReferenceEquals(null, addressAttribute))
            {
                addressAttribute.Value = "http://" + Name + "/test1/test2.svc";

            }
        }
        doc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
    }

【问题讨论】:

    标签: c# xml wcf app-config service-reference


    【解决方案1】:

    app.config 在第一次读取时被进程缓存。如果要在运行时更改配置文件,则需要清除缓存并再次读取。你可以通过调用来做到这一点:

    ConfigurationManager.RefreshSection("system.serviceModel/client");
    

    您也可以在不通过 app.config 的情况下更改端点地址。只需在 WCF 客户端实例上设置 Endpoint 属性即可。

    【讨论】:

    • 即使在我更改地址之前将该行添加到 main 方法之后,有时它会使用旧地址并显示未找到。
    • 您必须在 更改地址之后刷新Section()。
    • 我换地址后放了还是没有改善。 SaveEndpointAddress("adsad-6/test1/test2.svc"); ConfigurationManager.RefreshSection("//system.serviceModel//client"); 每次第二次都正确...有什么想法吗?:(
    • 您不需要转义正斜杠。将所有“//”替换为“/”。而且您不需要前导正斜杠。只需使用我在答案中输入的代码即可。
    • 这就是我现在所拥有的:SaveEndpointAddress("adsad-6/test1/test2.svc"); ConfigurationManager.RefreshSection("system.serviceModel/client"); 我还在保存文件之前放置了相同的刷新行。仍然是程序只有在我第二次运行时才正确:(
    【解决方案2】:

    您可以在服务实例创建本身中控制服务地址。无需更新配置文件(不需要时)。

    检查下面的简单实现,此方法将为您提供服务客户端(假设 ServiceClient 为代理)。

        public ServiceClient EndpointAddressConfiguration()
        {
            ServiceClient newClient = new ServiceClient("httpBindinConfigName","http://hostname/service.svc");
            return newClient;
        }
    

    这里我们使用现有的绑定配置(httpBindinConfigName 位于配置部分)。如果需要,我们也可以更改绑定配置。

    【讨论】:

      猜你喜欢
      • 2010-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      相关资源
      最近更新 更多