我的程序中,已经配置了webserivce了,但是无法再开发环境使用,我想拿到测试环境使用,而webservice又只能在开发环境调用。这个时候,为了解决这种尴尬问题,我只能先将就着用开发时的webservice。
在我的web.config中,有如下终结点配置,但是我的程序可能,我希望能在测试环境中,能够根据web.config中的配置来使用。
<system.serviceModel>
<client>
<endpoint address="http://192.168.254.120:7001/ui/services/OnlineBussService"
binding="basicHttpBinding" bindingConfiguration="OnlineBussServiceSoapBinding"
contract="ABCLifeFTP.OnlineBussWebService" name="OnlineBussService" />
</client>
</system.serviceModel>
原先开发环境的调用webservice已经写好了,但是现在不得不为了动态使用配置而新增代码,添加了如下的代码:
//获取web.config中的终结点配置
public string GetEndPointAddressByName(string name)
{
string configUrl = "";
ClientSection clientSection = (ClientSection)WebConfigurationManager.GetSection("system.serviceModel/client"); //找到终结点标签
if (clientSection == null && clientSection.Endpoints.Count <= 0) //判断是否存在
{
RecordLog<string>("Recive:[GetEndPointAddressByName]", "Endpoint地址未配置");
return null;
}
foreach (ChannelEndpointElement cee in clientSection.Endpoints) //循环终结点,找到需要使用的配置
{
if (cee.Name == name && cee.Address != null)
{
configUrl = clientSection.Endpoints[0].Address.AbsoluteUri; //获取地址
RecordLog<string>("Recive:[GetEndPointAddressByName.configUrl]", configUrl);
return configUrl;
}
}
RecordLog<string>("Recive:[GetEndPointAddressByName]", "Endpoint地址未配置或配置错误,调用的终端节点名称:" + name);
return null;
}
而在调用web.config代码中,也需要做修改:
OnlineBussWebServiceClient OBWSC = null; //定义接口Client
try
{
string str = GetEndPointAddressByName("OnlineBussService"); //根据此名称,调用上面的方法,获取webservice的地址
if (str != null)
OBWSC = new OnlineBussWebServiceClient(new BasicHttpBinding(), new EndpointAddress(str)); //根据地址去实例化接口
else
return;
if (OBWSC == null)
{
RecordLog<string>("Recive:[SendPolicyInfo.OBWSC]", "服务调用失败");
return;
}
RecordLog<OnlineBussWebServiceClient>("Recive:[SendPolicyInfo.OBWSC]", OBWSC);
}
catch (Exception ex)
{
RecordLog<string>("Recive:[SendPolicyInfo.Exception1]", ex.Message);
return;
}
使用接口方法:
string sss=OBWSC .GetName("Test");
就这样,我的程序,就可以根据web.config文件中配置的地址,来动态使用接口了,在测试环境使用就不成问题了。