方式一:需要填写地址,不能映射每个方法
工具类
- 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
- {
- ///
- /// 生成dll文件保存到本地
- ///
- /// WebService地址
- /// 类名
- /// 方法名
- /// 保存dll文件的路径
- 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)
- {
- //缓存过期删除dll
- File.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";
- // 调用WebServiceHelper
- WebServiceHelper.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 = { "
ZH230911DR8141 " }; - // 调用访问,获取方法返回值
- 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
- {
- ///
- /// 输出的dll文件名称
- ///
- private static string m_OutputDllFilename;
-
- ///
- /// WebService代理类名称
- ///
- private static string m_ProxyClassName;
-
- ///
- /// WebService代理类实例
- ///
- private static object m_ObjInvoke;
-
- ///
- /// 接口方法字典
- ///
- private static Dictionary
m_MethodDic = new Dictionary(); -
- ///
- /// 创建WebService,生成客户端代理程序集文件
- ///
- ///
- ///
- 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)
- {
- // 格式化WSDL
- ServiceDescription 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();
- }
- else
- error = "打开WebServiceUrl失败";
- }
- catch (Exception ex)
- {
- error = "异常:"+ex.Message;
- //Log.WriteLog(error);
- }
- return false;
- }
-
- ///
- /// 反射构建Methods
- ///
- 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);
- }
- }
- }
- ///
- /// 获取请求响应
- ///
- ///
- ///
- ///
- 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 = "
ZH230911DR8141 "; - 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");