c#動態改變webservice的url訪問地址
阿新 • • 發佈:2019-01-27
1、新增一個App.config配置檔案。
2、配置服務http://Lenovo-PC:80/EvisaWS/WharfService?wsdl,那麼在上面的檔案中就會自動生成服務的配置:
複製程式碼 程式碼如下:<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="WharfWSBeanBinding" />
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://Lenovo-PC:80/EvisaWS/WharfService"
binding="basicHttpBinding" bindingConfiguration="WharfWSBeanBinding"
contract="WharfService.WharfWSBean" name="WharfService" />
</client>
</system.serviceModel>
</configuration>
3、動態新增新的地址,後面的?wsdl沒有也可以:
複製程式碼 程式碼如下:WharfWSBeanClient c = new WharfWSBeanClient("WharfService", "新的地址例如:http://192.168.1.194/EvisaWS/WharfService?wsdl");
4、新伺服器的地址可以存放到登錄檔或者環境變數裡面,下面是新存放到登錄檔,然後再存放到環境變數裡,訪問的時候先從環境變數裡面獲取:
4.1 存到登錄檔:
複製程式碼 程式碼如下:RegistryKey key = Registry.LocalMachine.CreateSubKey(@"Software\Client");
key.SetValue("ip", "192.168.1.1");
4.2 從登錄檔獲取值:
String ip =Environment.GetEnvironmentVariable("myconfigip");
if (ip == null || ip.Equals(""))
{
RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\Client");
ip = key.GetValue("myip") as string;
Environment.SetEnvironmentVariable("myconfigip", ip);
}
上面是先從環境變數裡面取,如果沒有則從登錄檔取,之後又存放到環境變數裡,以後在程序內訪問時直接從環境變數裡面取就可以了。