/// <summary> /// 通过webservice接口,自动创建代码类 /// </summary> /// <param name="url"></param> /// <param name="classname"></param> /// <param name="methodname"></param> /// <returns></returns> public static Type GetWebServiceType(string url, string classname) { #region 实现过程 if ((classname == null) || (classname == "")) { classname = WebServiceHelper.GetWsClassName(url); } try { //获取WSDL ,得到sdi WebClient wc = new WebClient(); Stream stream = wc.OpenRead(url + "?WSDL"); ServiceDescription sd = ServiceDescription.Read(stream); ServiceDescriptionImporter sdi = new ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, "", ""); //得到ccu string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling"; CodeNamespace cn = new CodeNamespace(@namespace); CodeCompileUnit ccu = new CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); //设定编译参数 CompilerParameters cplist = new CompilerParameters(); cplist.GenerateExecutable = false; cplist.GenerateInMemory = true; cplist.ReferencedAssemblies.Add("System.dll"); cplist.ReferencedAssemblies.Add("System.XML.dll"); cplist.ReferencedAssemblies.Add("System.Web.Services.dll"); cplist.ReferencedAssemblies.Add("System.Data.dll"); //编译 CSharpCodeProvider icc = new CSharpCodeProvider(); CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu); //出错信息 if (true == cr.Errors.HasErrors) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors) { sb.Append(ce.ToString()); sb.Append(System.Environment.NewLine); } throw new Exception(sb.ToString()); } //自动创建类信息 Assembly assembly = cr.CompiledAssembly; Type t = assembly.GetType(@namespace + "." + classname, true, true); return(t); } catch (Exception e) { MyLog.WriteExceptionLog("WebServiceHelper.GetWebServiceType", e, string.Format("\r\n\turl:{0}", url)); return(null); } #endregion }
//调用例子: /* * string url = "http://localhost/IPwebservice/sysservice.asmx"; * string methodname = "Login"; * Hashtable htParam = new Hashtable(); * htParam.Add("userCode", "150043"); * htParam.Add("userPassword", ""); * htParam.Add("appCode", "ip"); * string ret = HTTPS.WebServiceHelper.InvokeWebService(url, methodname, htParam).ToString(); */ /// < summary> /// 动态调用web服务 /// < /summary> /// < param name="url">WSDL服务地址< /param> /// < param name="methodname">方法名< /param> /// < param name="htParam">参数< /param> /// < returns>< /returns> public static object InvokeWebService(string url, string methodname, Hashtable htParam) { return(WebServiceHelper.InvokeWebService(url, null, methodname, htParam)); }