WebService asmx生成的wsdl 修改 location

C#中使用webservice接口的时候,返给服务器的IP地址是带上了端口号的。但是有时候不能要那个端口(比如用nginx做了转发),网上有人说修改nginx的配置,在头信息上加host和server_port,如这篇文章:

解决nginx反响代理web service的soap:address location问题

但是这篇文章中的例子是nginx监听的端口和后端所代理的服务的端口是一致的,那么只需要设置proxy_set_header Host $host:$server_port;

或许是.net的wsdl生成和其它语言的wsdl生成机制略有不同,.net生成wsdl获取端口总是本机发布的程序的端口,此时就需要在服务端处理一下(处理内容就是后面的代码)。此外,需要在配置文件中web.config中的system.web中添加一些东西:

<webServices>

<protocols>

<add name="HttpGet"/>

<add name="HttpPost"/>

<add name="HttpSoap"/>

</protocols>

<webServices>
<soapExtensionReflectorTypes>
<add type="WsdlPortReplace.MyReflector,WsdlPortReplace" />
</soapExtensionReflectorTypes>
</webServices>

</webServices>

我在实际处理过程中,没有设置httpget和httppost,就是设置了httpsoap

然后新建一个类项目,只有一个class文件,代码:

using System;
using System.Web.Services.Description;
using System.Configuration;

namespace WsdlPortReplace
{
    public class MyReflector : SoapExtensionReflector
    {
        public override void ReflectMethod()
        {
            //throw new NotImplementedException();
        }

        public override void ReflectDescription()
        {
            String localIISPort = ConfigurationManager.AppSettings["localIISPort"];
            String proxyPort = ConfigurationManager.AppSettings["proxyPort"];
            ServiceDescription des = ReflectionContext.ServiceDescription;
            foreach (Service service in des.Services)
            {
                foreach (Port port in service.Ports)
                {
                    foreach (ServiceDescriptionFormatExtension extension in port.Extensions)
                    {
                        SoapAddressBinding binding = extension as SoapAddressBinding;
                        if (binding != null)
                        {
                            binding.Location = binding.Location.Replace(":" + localIISPort, ":" + proxyPort);
                        }
                        //else
                        //{
                        //    HttpAddressBinding httpBinding = extension as HttpAddressBinding;
                        //    if (httpBinding != null)
                        //    {
                        //        httpBinding.Location = location;//httpBinding.Location.Replace("8099", "9080");
                        //    }
                        //    else
                        //    {
                        //        Soap12AddressBinding soap12Binding = new Soap12AddressBinding();
                        //        if (soap12Binding != null) {
                        //            soap12Binding.Location = location;//soap12Binding.Location.Replace("8099", "9080");
                        //        }
                        //    }

                        //}

                    }
                }
            }
        }
    }
}

然后把生成的dll文件放到webservice所在的程序的bin文件夹下

参考地址:

https://www.cnblogs.com/tiancai/p/13528153.html

https://q.cnblogs.com/q/58713/

posted @ 2021-09-01 09:04  八方鱼  阅读(1720)  评论(0)    收藏  举报