在项目中添加引用webservice是相对固定的,当webservice更换地址后需要将整个项目重新添加webservice引用,而动态配置则可以在webservice地址发生改变时只改动配置文件即可实现整个项目的webservice的引用的地址的更改,方便了操作。特别是在程序开发测试阶段,可以先用本机的webservice测试,在测试成功后再发布到服务器上。具体的实现步骤如下:
1、添加本机的webservice引用
添加后的图片:
在由引用webservice后,双击既可看到系统自动添加的代码,如:
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="GlobalWeatherSoap", Namespace="http://www.webserviceX.NET")]
public partial class GlobalWeather : System.Web.Services.Protocols.SoapHttpClientProtocol {
/// <remarks/>
public GlobalWeather() {
this.Url = "http://www.webservicex.net/globalweather.asmx";
}
}
动态引用webservice就是继承系统自动添加的引用,并且将其中的url换位参数传递,默认的没有参数的就是调用引用时的代码,在更换webservice地址后需要引用带参数的相应的函数,这样既可以直接调试我们的系统,又可以在webservice地址发生改变时加以转换。
2、生成动态引用的继承类
需要引用的单元:
using System.Diagnostics;
using System.ComponentModel;
using System.Web.Services;
需要生成的继承类:
/// <summary>
/// 动态引用webservice
/// </summary>
[DebuggerStepThrough(), DesignerCategory("code"), WebServiceBinding(Name = "", Namespace = "")]
class Dyn_Weather : WeatherService.GlobalWeather
{
internal Dyn_Weather()
: base()
{
this.Url = "http://www.webservicex.net/globalweather.asmx";
}
internal Dyn_Weather(string ip) //带参数的构造函数,在调用时制定ip地址
: base()
{
this.Url=string.Format("http://{0}/globalweather.asmx",ip);
}
}
3、调用动态webservice
Dyn_Weather dy = new Dyn_Weather("192.168.1.10");//制定webservice的ip地址
lblDeviceid.Text =dy.GetWeather("beijing", "china").ToString();
这样只需在构造函数时制定webservice服务的ip地址就可以实现webservice的动态配置,对于项目开发带来了方便性。