我们经常要在项目中添加服务引用,去调用各种服务啊,接口啊。就拿调用接口来讲,当你添加了服务引用后就会有一个项目congfig配置文件,里面可以配置接口信息,像地址名称等等,我们就可以通过修改这个congfig文件来动态调用各个接口了,当然要自己添加一个表单在界面进行修改。
先来看看这个配置了接口信息的配置文件内容:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_aaaaaaaa" messageEncoding="Mtom">
<security mode="None" />
</binding>
</wsHttpBinding>
</bindings>
<client>
<endpoint address="http://192.55.36.756:1458/Svr/HelloWorld.svc"
binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_HelloWorld"
contract="HelloService.HelloWorld" name="WSHttpBinding_HelloWorld" />
</client>
</system.serviceModel>
</configuration>
我们主要就是操作客户端的endpoint里的内容:
读取操作:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ClientSection clientSection = config.GetSection("system.serviceModel/client") as ClientSection;
string endpointName = “Hello”;
foreach (ChannelEndpointElement item in clientSection.Endpoints)
{
//判断Endpoints节点中有没有Name为endpointName
if (item.Name == endpointName) {
//输出接口地址
return item.Address.ToString();
}
}
写入操作:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ClientSection clientSection = config.GetSection("system.serviceModel/client") as ClientSection;
string endpointName = "Hello";
string address = "http://192.32.02.163:8521/hel/Printed.svc";
foreach (ChannelEndpointElement item in clientSection.Endpoints)
{
//是否存在endpointName
if (item.Name != endpointName)
continue;
//存在就将接口地址修改为address
item.Address = new Uri(address);
break;
}
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("system.serviceModel");
如果有问题,或是想法可以留言噢,一天之内就会回复。