方式一:需要填写地址,不能映射每个方法
工具类
using System;
using System.CodeDom.Compiler;
using System.CodeDom;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web.Services.Description;
using System.Xml.Serialization;
using System.Web;
using System.Web.Caching;namespace ReportTest
{public class WebServiceHelper{/// <summary>/// 生成dll文件保存到本地/// </summary>/// <param name="url">WebService地址</param>/// <param name="className">类名</param>/// <param name="methodName">方法名</param>/// <param name="filePath">保存dll文件的路径</param>public static void CreateWebServiceDLL(string url, string className, string methodName, string filePath){// 1. 使用 WebClient 下载 WSDL 信息。WebClient web = new WebClient();Stream stream = web.OpenRead(url);// 2. 创建和格式化 WSDL 文档。ServiceDescription description = ServiceDescription.Read(stream);//如果不存在就创建file文件夹if (Directory.Exists(filePath) == false){Directory.CreateDirectory(filePath);}if (File.Exists(filePath + className + "_" + methodName + ".dll")){//判断缓存是否过期var cachevalue = HttpRuntime.Cache.Get(className + "_" + methodName);if (cachevalue == null){//缓存过期删除dllFile.Delete(filePath + className + "_" + methodName + ".dll");}else{// 如果缓存没有过期直接返回return;}}// 3. 创建客户端代理代理类。ServiceDescriptionImporter importer = new ServiceDescriptionImporter();// 指定访问协议。importer.ProtocolName = "Soap";// 生成客户端代理。importer.Style = ServiceDescriptionImportStyle.Client;importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync;// 添加 WSDL 文档。importer.AddServiceDescription(description, null, null);// 4. 使用 CodeDom 编译客户端代理类。// 为代理类添加命名空间,缺省为全局空间。CodeNamespace nmspace = new CodeNamespace();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 = filePath + className + "_" + methodName + ".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");// 生成dll文件,并会把WebService信息写入到dll里面CompilerResults result = provider.CompileAssemblyFromDom(parameter, unit);if (result.Errors.HasErrors){// 显示编译错误信息System.Text.StringBuilder sb = new StringBuilder();foreach (CompilerError ce in result.Errors){sb.Append(ce.ToString());sb.Append(System.Environment.NewLine);}throw new Exception(sb.ToString());}//记录缓存var objCache = HttpRuntime.Cache;// 缓存信息写入dll文件objCache.Insert(className + "_" + methodName, "1", null, DateTime.Now.AddMinutes(5), TimeSpan.Zero, CacheItemPriority.High, null);}}
}
调用方法:
// 读取配置文件,获取配置信息string url = "http://127.0.0.1:8080/integration_web/services/GEDataServices?wsdl";string className = "IGEDataServicesService";string methodName = "queryExamInfo";string filePath = "D:/my";// 调用WebServiceHelperWebServiceHelper.CreateWebServiceDLL(url, className, methodName, filePath);// 读取dll内容byte[] filedata = File.ReadAllBytes(filePath + className + "_" + methodName + ".dll");// 加载程序集信息Assembly asm = Assembly.Load(filedata);Type t = asm.GetType(className);// 创建实例object o = Activator.CreateInstance(t);MethodInfo method = t.GetMethod(methodName);// 参数object[] args = { "<?xml version=\"1.0\" encoding=\"GBK\" ?><request><patientid></patientid><accessionid>ZH230911DR8141</accessionid></request>" };// 调用访问,获取方法返回值string result = method.Invoke(o, args).ToString();//输出返回值textBox1.AppendText("result is:" + result + "\r\n");
方式二:需要提前写好方法名,调用简单像调用类方法一样
using System;
using System.CodeDom.Compiler;
using System.CodeDom;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using System.IO;
using System.Web.Services.Description;namespace ReportGetWS
{public enum EMethod{updCriticalValues,queryExamInfo,printFilm,downloadReport,updateReportStatus,queryFilmPrintStatus,}public class WSHelper{/// <summary>/// 输出的dll文件名称/// </summary>private static string m_OutputDllFilename;/// <summary>/// WebService代理类名称/// </summary>private static string m_ProxyClassName;/// <summary>/// WebService代理类实例/// </summary>private static object m_ObjInvoke;/// <summary>/// 接口方法字典/// </summary>private static Dictionary<EMethod, MethodInfo> m_MethodDic = new Dictionary<EMethod, MethodInfo>();/// <summary>/// 创建WebService,生成客户端代理程序集文件/// </summary>/// <param name="error"></param>/// <returns></returns>public static bool CreateWebService(out string error){try{error = string.Empty;m_OutputDllFilename = "report.dll";m_ProxyClassName = "IGEDataServicesService";string webServiceUrl = "http://127.0.0.1:8080/integration_web/services/GEDataServices?wsdl";// 如果程序集已存在,直接使用if (File.Exists(Path.Combine(Environment.CurrentDirectory, m_OutputDllFilename))){BuildMethods();return true;}//使用 WebClient 下载 WSDL 信息。WebClient web = new WebClient();Stream stream = web.OpenRead(webServiceUrl);//创建和格式化 WSDL 文档。if (stream != null){// 格式化WSDLServiceDescription description = ServiceDescription.Read(stream);// 创建客户端代理类。ServiceDescriptionImporter importer = new ServiceDescriptionImporter{ProtocolName = "Soap",Style = ServiceDescriptionImportStyle.Client,CodeGenerationOptions =CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync};// 添加 WSDL 文档。importer.AddServiceDescription(description, null, null);//使用 CodeDom 编译客户端代理类。CodeNamespace nmspace = new CodeNamespace();CodeCompileUnit unit = new CodeCompileUnit();unit.Namespaces.Add(nmspace);ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit);CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");CompilerParameters parameter = new CompilerParameters{GenerateExecutable = false,// 指定输出dll文件名。OutputAssembly = m_OutputDllFilename};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);// 使用 Reflection 调用 WebService。if (!result.Errors.HasErrors){BuildMethods();return true;}else{error = "反射生成dll文件时异常";}stream.Close();stream.Dispose();}elseerror = "打开WebServiceUrl失败";}catch (Exception ex){error = "异常:"+ex.Message;//Log.WriteLog(error);}return false;}/// <summary>/// 反射构建Methods/// </summary>private static void BuildMethods(){Assembly asm = Assembly.LoadFrom(m_OutputDllFilename);Type[] types = asm.GetTypes();Type asmType = asm.GetType(m_ProxyClassName);m_ObjInvoke = Activator.CreateInstance(asmType);var methods = Enum.GetNames(typeof(EMethod)).ToList();foreach (var item in methods){var methodInfo = asmType.GetMethod(item);if (methodInfo != null){var method = (EMethod)Enum.Parse(typeof(EMethod), item);m_MethodDic.Add(method, methodInfo);}}}/// <summary>/// 获取请求响应/// </summary>/// <param name="method"></param>/// <param name="para"></param>/// <returns></returns>public static string GetResponseString(EMethod method, params object[] para){string result = string.Empty;try{if (m_MethodDic.ContainsKey(method)){var temp = m_MethodDic[method].Invoke(m_ObjInvoke, para);if (temp != null)result = temp.ToString();}}catch { }return result;}}
}
调用方式:
textBox1.AppendText("start get\r\n");string error = "";string param1 = "<?xml version=\"1.0\" encoding=\"GBK\" ?><request><patientid></patientid><accessionid>ZH230911DR8141</accessionid></request>";bool succ = WSHelper.CreateWebService(out error);textBox1.AppendText("error is:" + error + "\r\n");textBox1.AppendText("succ is:" + succ + "\r\n");string result = WSHelper.GetResponseString(EMethod.queryExamInfo, param1);textBox1.AppendText("result is:" + result + "\r\n");