WebServiceHelper 中使用 SoapAddressBinding 动态修改 WebService 的 URL 地址

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 );

    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值