动态修改配置文件web服务地址

关于动态添加WebService引用的地址的问题,我分析了一下,解决方案如下:
1.在应用程序中添加配置文件(如Winform的一般是app.config,webform的一般是web.config),在<appSettings>目录下添加一个配置WebService引用地址的节点,如:<add key="webServiceAddr" value="http://192.168.1.105:800/TestWebService.asmx?wsdl"/>
2.项目添加Web服务引用,如引用名为ServiceCenter,引用成功后,在打开目录Web References》ServiceCenter》Reference.map》Reference.cs的Reference.cs文件,这是一个WebService代理类。
不同的WebService生成的代理类不同。构造函数如:
public TestWebService() {
this.Url = global::WebServiceApp.Properties.Settings.Default.WebServiceApp_ServiceCenter_TestWebService;
if ((this.IsLocalFileSystemWebService(this.Url) == true)) {
this.UseDefaultCredentials = true;
this.useDefaultCredentialsSetExplicitly = false;
}
else {
this.useDefaultCredentialsSetExplicitly = true;
}
}
重新添加一个构造函数,带有WebService引用地址的参数:
public TestWebService(string url)
{
if (!string.IsNullOrEmpty(url))
{
this.Url = url;
}
else
{
this.Url = global::WebServiceApp.Properties.Settings.Default.WebServiceApp_ServiceCenter_TestWebService;  
}
if ((this.IsLocalFileSystemWebService(this.Url) == true))
{
this.UseDefaultCredentials = true;
this.useDefaultCredentialsSetExplicitly = false;
}
else
{
this.useDefaultCredentialsSetExplicitly = true;
}
}
3.在应用程序中应用
private void button1_Click(object sender, EventArgs e)
{
string result = string.Empty;
string serviceAddr = string.Empty;
try
{
serviceAddr = System.Configuration.ConfigurationManager.AppSettings["webServiceAddr"].ToString();
//此处调用的是我们自己定义的构造函数,参数为WebService引用的地址
ServiceCenter.TestWebService webService = new WebServiceApp.ServiceCenter.TestWebService(serviceAddr);
result = webService.Test();
}
catch (Exception ex)
{
result = ex.Message;
}
MessageBox.Show(serviceAddr + "++++" + result);
}
4.修改WebService引用地址:
在Winform应用程序中,app.config等应用程序配置文件在生成的时候自动生成到了bin目录下面的应用程序名.exe.config文件,修改里面的webServiceAddr节点即可。
需要注意的一点就是,如果生成的时候把app.config文件也生成到了bin目录下,此时修改app.config里面的配置是无效,还必须得修改(应用程序名.exe.config)这个文件。如果是把webservice引用地址放在自定义的的xml文件中,则生成到bin目录下,响应bin目录下的xml文件即可。

posted @ 2014-03-11 11:51  小小戒  阅读(1367)  评论(0编辑  收藏  举报