.net动态调用wsdl soap提交

   因为我自己原来没有动态调用过wsdl,所有调用期间找了很多例子,浪费了很多时间,现在项目结束把这个动态调用方法放上来,以供参考

 

string eg= "https://xxxxxxxxx/scan?wsdl";//需要调用方法的地址

string url= "https://xxxxxxxxx/scan“;

 String str=  "hksfafasf";//方法所需参数

WebServiceAgent ag = new WebServiceAgent(url);

//调用方法获取输出结果 

string resultStr = (string)ag.Invoke("scanPay", str); //scanPay方法名称

public class WebServiceAgent

    {
        private object agent;
        private Type agentType;
        private const string CODE_NAMESPACE = "Beyondbit.WebServiceAgent.Dynamic";

        public WebServiceAgent(string url)
        {
            XmlTextReader reader = new XmlTextReader(url + "?wsdl");

            //创建和格式化 WSDL 文档    
            ServiceDescription sd = ServiceDescription.Read(reader);

            //创建客户端代理代理类    
            ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
            sdi.AddServiceDescription(sd, null, null);

            //使用 CodeDom 编译客户端代理类    
            CodeNamespace cn = new CodeNamespace(CODE_NAMESPACE);
            CodeCompileUnit ccu = new CodeCompileUnit();
            ccu.Namespaces.Add(cn);
            sdi.Import(cn, ccu);
            CSharpCodeProvider icc = new CSharpCodeProvider();
            CompilerParameters cp = new CompilerParameters(new string[] { "System.Data.dll" }); // 在此添加所缺的dll,比如"System.Data.dll"  
            CompilerResults cr = icc.CompileAssemblyFromDom(cp, ccu);
            agentType = cr.CompiledAssembly.GetTypes()[0];
            agent = Activator.CreateInstance(agentType);
        }

        public object Invoke(string methodName, params object[] args)
        {
            MethodInfo mi = agentType.GetMethod(methodName);
            return this.Invoke(mi, args);
        }

        public object Invoke(MethodInfo method, params object[] args)
        {
            return method.Invoke(agent, args);
        }

        public MethodInfo[] Methods
        {
            get
            {
                return agentType.GetMethods();
            }
        }
    }  

 

总结:接口调通之后感觉也是很简单,但是之前是真的不知道发生了什么,记录一下

posted on 2018-06-21 18:14  Smile向前  阅读(465)  评论(0编辑  收藏  举报