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);
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 记录一下项目中的需求完成流程图示例,使用的是使用vue-cli搭建的项目,配合gojs来实现的,附上截图一份: 由...
    李海鹏_f321阅读 10,199评论 4 2
  • 常见的远程调用协议与技术 IOS的七层模型: Socket通信:Socket属于传输层,它是对TCP/IP协议的实...
    爱宝宝n阅读 5,836评论 0 0
  • 原链接:http://www.cnblogs.com/langtianya/p/3757993.html JDK各...
    把爱放下会走更远阅读 4,765评论 0 10
  • 对于很多刚接触java语言的初学者来说,要了解一门语言,最好的方式就是要能从基础的版本进行了解,升级的过程,以及升...
    timothyue1阅读 2,615评论 0 1
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,408评论 19 139