标签:
这两天给公司写一个调用接口的程序,接口采用WebService!
本打算将这个工具写成通用的,但是微软给出的调用WebService的方法必须添加该WebService引用,
这样的方式不免太过于死板,无法动态调用,于是在网上查了很多相关解决办法!自己封装成了一个函数,发布出来,做个纪念!
using System.Net; using System.IO; using System.Web.Services.Description; using System.CodeDom; using System.CodeDom.Compiler; using System.Reflection; using System; using System.Xml.Serialization; namespace WebServiceToOracle.Common { /// <summary> /// Web服务操作类 /// Author:梁 /// Time:2014-4-17 /// </summary> public class WebServiceHelper { /// <summary> /// 动态调用WebService /// </summary> /// <param name="url">WebService地址</param> /// <param name="function">欲调用的WebService接口函数</param> /// <param name="parameters">接口参数</param> /// <returns>接口数据</returns> public static string DynamicInvocationWebService(string url,string function,string[] parameters) { WebClient client = new WebClient(); if (url.IndexOf("?WSDL") == -1) { url = url + "?WSDL"; } Stream stream = client.OpenRead(url); ServiceDescription description = ServiceDescription.Read(stream); //创建客户端代理代理类。 ServiceDescriptionImporter importer = new ServiceDescriptionImporter(); //指定访问协议。 importer.ProtocolName = "Soap"; //生成客户端代理。 importer.Style = ServiceDescriptionImportStyle.Client; importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync; //添加WSDL文档。 importer.AddServiceDescription(description, null, null); //命名空间 CodeNamespace nmspace = new CodeNamespace(); nmspace.Name = "SearchAmountOfProduct"; 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 = "DynamicInvocationWebService.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("DynamicInvocationWebService.dll"); Type t = asm.GetType("SearchAmountOfProduct.SearchAmountOfProduct"); object o = Activator.CreateInstance(t); MethodInfo method = t.GetMethod(function); String item = (String)method.Invoke(o, parameters); return item; } } }
标签:
原文地址:http://www.cnblogs.com/fuhua/p/5877807.html