动态调用webservice
Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--> protected string TestService(string strurl,string methodname) { System.Net.WebClient client = new System.Net.WebClient(); String url = ""+strurl+"?WSDL"; System.IO.Stream stream = client.OpenRead(url); System.Web.Services.Description.ServiceDescription description = System.Web.Services.Description.ServiceDescription.Read(stream); System.Web.Services.Description.ServiceDescriptionImporter importer = new System.Web.Services.Description.ServiceDescriptionImporter();//创建客户端代理代理类。 importer.ProtocolName = "Soap"; //指定访问协议。 importer.Style = System.Web.Services.Description.ServiceDescriptionImportStyle.Client; //生成客户端代理。 importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync; importer.AddServiceDescription(description, null, null); //添加WSDL文档。 CodeNamespace nmspace = new CodeNamespace(); //命名空间 nmspace.Name = "TestWebService"; 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.OutputAssembly = "MyTest.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"); CompilerResults result = provider.CompileAssemblyFromDom(parameter, unit); if (result.Errors.HasErrors) { // 显示编译错误信息 } Assembly asm = Assembly.LoadFrom("MyTest.dll");//加载前面生成的程序集 Type t = asm.GetType("TestWebService.Service"); object o = Activator.CreateInstance(t); MethodInfo method = t.GetMethod(methodname);//GetPersons是服务端的方法名称,你想调用服务端的什么方法都可以在这里改,最好封装一下 //String[] item = (String[])method.Invoke(o, null); //注: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 method.Invoke(o, null).ToString(); }