C#动态调用WebService
public class WSHelper { /// < summary> /// 动态调用web服务 /// < /summary> /// < param name="url">WSDL服务地址< /param> /// < param name="methodname">方法名< /param> /// < param name="args">参数< /param> /// < returns>< /returns> public static object InvokeWebService(string url, string methodname, object[] args) { return WSHelper.InvokeWebService(url, null, methodname, args); } /// < summary> /// 动态调用web服务 /// < /summary> /// < param name="url">WSDL服务地址< /param> /// < param name="classname">类名< /param> /// < param name="methodname">方法名< /param> /// < param name="args">参数< /param> /// < returns>< /returns> public static object InvokeWebService(string url, string classname, string methodname, params object[] args) { string @namespace = "Model";//"EnterpriseServerBase.WebService.DynamicWebCalling"; if ((classname == null) || (classname == "")) { classname = WSHelper.GetWsClassName(url); } try { //获取WSDL WebClient wc = new WebClient(); Stream stream = wc.OpenRead(url + "?WSDL"); ServiceDescription sd = ServiceDescription.Read(stream); ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();//创建客户端代理代理类。 sdi.AddServiceDescription(sd, "", ""); CodeNamespace cn = new CodeNamespace(@namespace);//这里随便指定一个命名空间,但要与后面的一致 //生成客户端代理类代码 CodeCompileUnit ccu = new CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); CSharpCodeProvider icc = new CSharpCodeProvider(); //设定编译参数 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"); //编译代理类 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()); } //生成代理实例,并调用方法 System.Reflection.Assembly assembly = cr.CompiledAssembly; Type t = assembly.GetType(@namespace + "." + classname, true, true); object obj = Activator.CreateInstance(t); System.Reflection.MethodInfo mi = t.GetMethod(methodname); return mi.Invoke(obj, args); } catch (Exception ex) { throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace)); } } private static string GetWsClassName(string wsUrl) { string[] parts = wsUrl.Split('/'); string[] pps = parts[parts.Length - 1].Split('.'); return pps[0]; } public static byte[] SerializeObject(object pObj) { if (pObj == null) return null; System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(memoryStream, pObj); memoryStream.Position = 0; byte[] read = new byte[memoryStream.Length]; memoryStream.Read(read, 0, read.Length); memoryStream.Close(); return read; } public static object InvokeWebMethod(string _url, string _methodName, params object[] _params) { string @namespace = "proService"; string classname = WSHelper.GetWsClassName(_url); WebClient client = new WebClient(); Stream stream = client.OpenRead(_url + "?WSDL"); ServiceDescription description = ServiceDescription.Read(stream); ServiceDescriptionImporter importer = new ServiceDescriptionImporter();//创建客户端代理代理类。 importer.ProtocolName = "Soap"; //指定访问协议。 importer.Style = ServiceDescriptionImportStyle.Client; //生成客户端代理。 importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync; importer.AddServiceDescription(description, null, null); //添加WSDL文档。 CodeNamespace nmspace = new CodeNamespace(@namespace); //命名空间 这个命名空间可以自己取 CodeCompileUnit unit = new CodeCompileUnit(); unit.Namespaces.Add(nmspace); ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit); CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"); CompilerParameters parameter = new CompilerParameters(); parameter.GenerateExecutable = false; parameter.GenerateInMemory = true; //parameter.OutputAssembly = "Model.dll";//输出程序集的名称 parameter.ReferencedAssemblies.Add("System.dll"); parameter.ReferencedAssemblies.Add("System.XML.dll"); parameter.ReferencedAssemblies.Add("System.Web.Services.dll"); parameter.ReferencedAssemblies.Add("System.Data.dll"); parameter.ReferencedAssemblies.Add("Model.dll"); CompilerResults result = provider.CompileAssemblyFromDom(parameter, unit); if (result.Errors.HasErrors) { // 显示编译错误信息 } System.Reflection.Assembly assembly = result.CompiledAssembly; //Assembly asm = Assembly.LoadFrom("Model.dll");//加载前面生成的程序集 //Type t = asm.GetType("Test.AddTermService"); //前面的命名空间.类名,类必须是webservice中定义的 Type t = assembly.GetType(@namespace + "." + classname, true, true); object o = Activator.CreateInstance(t); MethodInfo method = t.GetMethod(_methodName);//GetPersons是服务端的方法名称,你想调用服务端的什么方法都可以在这里改,最好封装一下 object item = method.Invoke(o, _params); //注:method.Invoke(o, null)返回的是一个Object,如果你服务端返回的是DataSet,这里也是用(DataSet)method.Invoke(o, null)转一下就行了 //foreach (string str in item) // Console.WriteLine(str); //上面是根据WebService地址,模似生成一个代理类,如果你想看看生成的代码文件是什么样子,可以用以下代码保存下来,默认是保存在bin目录下面 //TextWriter writer = File.CreateText("MyTest.cs"); //provider.GenerateCodeFromCompileUnit(unit, writer, null); //writer.Flush(); //writer.Close(); return item; } }
//动态调用Webservice中的方法
//url Webservice地址
string url = "http://10.18.10.31:8666/TermRepairService.asmx";
//methodname方法名
//url Webservice地址
string url = "http://10.18.10.31:8666/TermRepairService.asmx";
//methodname方法名
string methodname = AppTool.GetAppSettingValue("AddTermMethod");
string ss = common.JsonClass.ObjToJsonString<Model.tblnewTerminal>(model);
object[] args = new object[1];
args[0] = ss;
string sret = string.Empty;
object obj = common.WSHelper.InvokeWebService(url, methodname, args);