为什么没有从更改后的地址调用WCF服务?
本文关键字:调用 地址 WCF 服务 为什么 | 更新日期: 2023-09-27 18:09:23
我尝试动态更改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);
}
app.config在第一次读取时被进程缓存。如果要在运行时更改配置文件,则需要清除缓存并再次读取它。你可以通过调用:
ConfigurationManager.RefreshSection("system.serviceModel/client");
你也可以不通过app.config修改端点地址。只需在WCF客户端实例上设置Endpoint
属性。
您可以在创建服务实例时控制服务地址。不需要更新配置文件(当不需要时)。
检查下面的简单实现,该方法将为您提供服务客户端(假设ServiceClient作为代理)。
public ServiceClient EndpointAddressConfiguration()
{
ServiceClient newClient = new ServiceClient("httpBindinConfigName","http://hostname/service.svc");
return newClient;
}
在这里我们使用现有的绑定配置(httpBindinConfigName在配置部分找到)。如果需要的话,我们也可以修改绑定配置。