C# 动态调用 WebService 时,对方给的 WSDL 中的 URL 是错误的,每次调用时都会报错:
1、未能解析此远程名称:xxxx;
2、Host not find;
3、Could not send message;
4、……
需要在 WebServiceHelper 中使用 SoapAddressBinding 动态修改 WebService 的 URL 地址,网上搜了好多教程都是动态调用的,没有发现一个在调用过程中替换 URL 地址的,自己实现了个,可以在以下 2 个地方进行处理:
1、生成和动态编译时修改:SoapAddressBinding;
// 获取 WSDL
WebClient client = new WebClient ();
Stream stream = client . OpenRead ( wsUrl + "?wsdl" );
ServiceDescription description = ServiceDescription . Read ( stream );
// 处理接口中的地址
ServiceCollection services = description . Services ;
foreach ( Service service in services )
{
PortCollection ports = service . Ports ;
foreach ( Port port in ports )
{
string portName = port . Name ;
ServiceDescriptionFormatExtensionCollection portExtensions = port . Extensions ;
foreach ( ServiceDescriptionFormatExtension extension in port . Extensions )
{
SoapAddressBinding binding = extension as SoapAddressBinding ;
if ( binding != null )
{
if ( binding . Location . ToLower () != wsUrl . ToLower ())
{
binding . Location = wsUrl ;
}
}
else
{
binding = new SoapAddressBinding ();
binding . Location = wsUrl ;
port . Extensions . Add ( binding );
}
}
}
}
2、生成和动态编译时通过反射 Assembly 修改 WebService 对象的 URL 属性;
// 获取类
Type type = assembly . GetType ( @namespace + "." + className , true , true );
// 实例类型对象
object obj = Activator . CreateInstance ( type );
// 修改 WebService 的请求地址 Url
PropertyInfo urlPropertyInfo = type . GetProperty ( "Url" );
if ( urlPropertyInfo != null )
{
object oldValue = urlPropertyInfo . GetValue ( obj , null );
object newValue = Convert . ChangeType ( wsUrl , urlPropertyInfo . PropertyType );
if ( Convert . ToString ( oldValue ). ToLower () != Convert . ToString ( newValue ). ToLower ())
{
urlPropertyInfo . SetValue ( obj , newValue , null );
}
}