我們經常要在項目中添加服務引用,去調用各種服務啊,接口啊。就拿調用接口來講,當你添加了服務引用後就會有一個項目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");
如果有問題,或是想法可以留言噢,一天之內就會回覆。