动态修改webservice的地址和端口可以通过修改web.config配置文件中的
- 读取web.config配置文件
首先,我们需要读取web.config配置文件中的
Configuration conf = ConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
ServiceModelSectionGroup smGroup = ServiceModelSectionGroup.GetSectionGroup(conf);
ServiceEndpointElementCollection seCollection = smGroup.Client.Endpoints;
上面代码中,首先使用ConfigurationManager类打开web.config配置文件,然后使用ServiceModelSectionGroup类获取
- 修改
节点
接下来,我们可以根据需求动态修改
foreach (ServiceEndpointElement se in seCollection)
{
se.Address = new Uri("http://192.168.0.100:8080/MyService");
se.BindingConfiguration = "NetTcpBinding_IMyService";
se.Name = "MyService_Endpoint";
}
上面代码中,我们遍历了
- 保存修改后的配置文件
最后,我们需要保存修改后的配置文件,以确保修改生效。代码示例如下:
conf.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("system.serviceModel");
上面代码中,我们使用Configuration类的Save方法将修改后的配置文件保存到磁盘,然后使用ConfigurationManager类的RefreshSection方法重新加载
示例说明:
假设我们在网站中添加了一个名为MyService的webservice,并且web.config配置文件中有如下
<client>
<endpoint address="http://localhost:8080/MyService"
binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_IMyService"
contract="IMyService"
name="WSHttpBinding_MyService" />
</client>
现在,我们想要动态修改它的地址和绑定配置,代码如下:
Configuration conf = ConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
ServiceModelSectionGroup smGroup = ServiceModelSectionGroup.GetSectionGroup(conf);
ServiceEndpointElementCollection seCollection = smGroup.Client.Endpoints;
foreach (ServiceEndpointElement se in seCollection)
{
if (se.Name == "WSHttpBinding_MyService")
{
se.Address = new Uri("http://192.168.0.100:8080/MyService");
se.BindingConfiguration = "NetTcpBinding_IMyService";
}
}
conf.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("system.serviceModel");
上面代码中,我们遍历了
另外一个示例是动态添加webservice的
Configuration conf = ConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
ServiceModelSectionGroup smGroup = ServiceModelSectionGroup.GetSectionGroup(conf);
ServiceEndpointElementCollection seCollection = smGroup.Client.Endpoints;
ServiceEndpointElement se = new ServiceEndpointElement();
se.Address = new Uri("http://192.168.0.100:8080/MyOtherService");
se.Binding = "basicHttpBinding";
se.BindingConfiguration = "BasicHttpBinding_IMyOtherService";
se.Contract = "IMyOtherService";
se.Name = "WSHttpBinding_MyOtherService";
seCollection.Add(se);
conf.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("system.serviceModel");
上面代码中,我们创建了一个新的
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:asp.net(c#)动态修改webservice的地址和端口(动态修改配置文件) - Python技术站