用博主这篇文章
Web Service学习笔记:动态调用WebService
的思路,构建了WebService ,
在实际上线的时候,发现 用户返回的数据发生相互串联,本来A 的结果 返回的是B的结果,B的结果返回的是A的结果,因为现在线使用,比较紧急。希望大家给个帮助。谢谢。
复制下面的代码,保证你正确。我的项目里就是这样子写的。
using ServiceModelEx; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; using System.Web.Services.Description; using System.CodeDom; using System.IO; using System.CodeDom.Compiler; using System.Reflection; using System.Collections; using System.Xml.Serialization; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { DynamicInvocation("http://localhost:29932/WebService1.asmx?WSDL"); } static void DynamicInvocation(string Uri) { Uri uri = new Uri(Uri); WebRequest webRequest = WebRequest.Create(uri); System.IO.Stream requestStream = webRequest.GetResponse().GetResponseStream(); ServiceDescription sd = ServiceDescription.Read(requestStream); string sdName = sd.Services[0].Name; ServiceDescriptionImporter servImport = new ServiceDescriptionImporter(); servImport.AddServiceDescription(sd, String.Empty, String.Empty); servImport.ProtocolName = "Soap"; servImport.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties; CodeNamespace nameSpace = new CodeNamespace(); CodeCompileUnit codeCompileUnit = new CodeCompileUnit(); codeCompileUnit.Namespaces.Add(nameSpace); ServiceDescriptionImportWarnings warnings = servImport.Import(nameSpace, codeCompileUnit); if (warnings == 0) { StringWriter stringWriter = new StringWriter (System.Globalization.CultureInfo.CurrentCulture); Microsoft.CSharp.CSharpCodeProvider prov = new Microsoft.CSharp.CSharpCodeProvider(); prov.GenerateCodeFromNamespace(nameSpace, stringWriter, new CodeGeneratorOptions()); string[] assemblyReferences = new string[2] { "System.Web.Services.dll", "System.Xml.dll" }; CompilerParameters param = new CompilerParameters(assemblyReferences); param.GenerateExecutable = false; param.GenerateInMemory = true; param.TreatWarningsAsErrors = false; CompilerResults results = new CompilerResults(new TempFileCollection()); results = prov.CompileAssemblyFromDom(param, codeCompileUnit); Assembly assembly = results.CompiledAssembly; Type[] types = assembly.GetTypes(); foreach (Type cls in types) { dynamic o = Activator.CreateInstance(cls); //这里写你调用的方法 Console.WriteLine(o.HelloWorld()); } } } } }