• c#对接webservice接口


    方式一:需要填写地址,不能映射每个方法

    工具类

    1. using System;
    2. using System.CodeDom.Compiler;
    3. using System.CodeDom;
    4. using System.Collections.Generic;
    5. using System.IO;
    6. using System.Linq;
    7. using System.Net;
    8. using System.Text;
    9. using System.Threading.Tasks;
    10. using System.Web.Services.Description;
    11. using System.Xml.Serialization;
    12. using System.Web;
    13. using System.Web.Caching;
    14. namespace ReportTest
    15. {
    16. public class WebServiceHelper
    17. {
    18. ///
    19. /// 生成dll文件保存到本地
    20. ///
    21. /// WebService地址
    22. /// 类名
    23. /// 方法名
    24. /// 保存dll文件的路径
    25. public static void CreateWebServiceDLL(string url, string className, string methodName, string filePath)
    26. {
    27. // 1. 使用 WebClient 下载 WSDL 信息。
    28. WebClient web = new WebClient();
    29. Stream stream = web.OpenRead(url);
    30. // 2. 创建和格式化 WSDL 文档。
    31. ServiceDescription description = ServiceDescription.Read(stream);
    32. //如果不存在就创建file文件夹
    33. if (Directory.Exists(filePath) == false)
    34. {
    35. Directory.CreateDirectory(filePath);
    36. }
    37. if (File.Exists(filePath + className + "_" + methodName + ".dll"))
    38. {
    39. //判断缓存是否过期
    40. var cachevalue = HttpRuntime.Cache.Get(className + "_" + methodName);
    41. if (cachevalue == null)
    42. {
    43. //缓存过期删除dll
    44. File.Delete(filePath + className + "_" + methodName + ".dll");
    45. }
    46. else
    47. {
    48. // 如果缓存没有过期直接返回
    49. return;
    50. }
    51. }
    52. // 3. 创建客户端代理代理类。
    53. ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
    54. // 指定访问协议。
    55. importer.ProtocolName = "Soap";
    56. // 生成客户端代理。
    57. importer.Style = ServiceDescriptionImportStyle.Client;
    58. importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync;
    59. // 添加 WSDL 文档。
    60. importer.AddServiceDescription(description, null, null);
    61. // 4. 使用 CodeDom 编译客户端代理类。
    62. // 为代理类添加命名空间,缺省为全局空间。
    63. CodeNamespace nmspace = new CodeNamespace();
    64. CodeCompileUnit unit = new CodeCompileUnit();
    65. unit.Namespaces.Add(nmspace);
    66. ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit);
    67. CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
    68. CompilerParameters parameter = new CompilerParameters();
    69. parameter.GenerateExecutable = false;
    70. // 可以指定你所需的任何文件名。
    71. parameter.OutputAssembly = filePath + className + "_" + methodName + ".dll";
    72. parameter.ReferencedAssemblies.Add("System.dll");
    73. parameter.ReferencedAssemblies.Add("System.XML.dll");
    74. parameter.ReferencedAssemblies.Add("System.Web.Services.dll");
    75. parameter.ReferencedAssemblies.Add("System.Data.dll");
    76. // 生成dll文件,并会把WebService信息写入到dll里面
    77. CompilerResults result = provider.CompileAssemblyFromDom(parameter, unit);
    78. if (result.Errors.HasErrors)
    79. {
    80. // 显示编译错误信息
    81. System.Text.StringBuilder sb = new StringBuilder();
    82. foreach (CompilerError ce in result.Errors)
    83. {
    84. sb.Append(ce.ToString());
    85. sb.Append(System.Environment.NewLine);
    86. }
    87. throw new Exception(sb.ToString());
    88. }
    89. //记录缓存
    90. var objCache = HttpRuntime.Cache;
    91. // 缓存信息写入dll文件
    92. objCache.Insert(className + "_" + methodName, "1", null, DateTime.Now.AddMinutes(5), TimeSpan.Zero, CacheItemPriority.High, null);
    93. }
    94. }
    95. }

    调用方法:

    1. // 读取配置文件,获取配置信息
    2. string url = "http://127.0.0.1:8080/integration_web/services/GEDataServices?wsdl";
    3. string className = "IGEDataServicesService";
    4. string methodName = "queryExamInfo";
    5. string filePath = "D:/my";
    6. // 调用WebServiceHelper
    7. WebServiceHelper.CreateWebServiceDLL(url, className, methodName, filePath);
    8. // 读取dll内容
    9. byte[] filedata = File.ReadAllBytes(filePath + className + "_" + methodName + ".dll");
    10. // 加载程序集信息
    11. Assembly asm = Assembly.Load(filedata);
    12. Type t = asm.GetType(className);
    13. // 创建实例
    14. object o = Activator.CreateInstance(t);
    15. MethodInfo method = t.GetMethod(methodName);
    16. // 参数
    17. object[] args = { "ZH230911DR8141" };
    18. // 调用访问,获取方法返回值
    19. string result = method.Invoke(o, args).ToString();
    20. //输出返回值
    21. textBox1.AppendText("result is:" + result + "\r\n");

    方式二:需要提前写好方法名,调用简单像调用类方法一样

    1. using System;
    2. using System.CodeDom.Compiler;
    3. using System.CodeDom;
    4. using System.Collections.Generic;
    5. using System.Configuration;
    6. using System.Linq;
    7. using System.Net;
    8. using System.Reflection;
    9. using System.Text;
    10. using System.Threading.Tasks;
    11. using System.Xml.Serialization;
    12. using System.IO;
    13. using System.Web.Services.Description;
    14. namespace ReportGetWS
    15. {
    16. public enum EMethod
    17. {
    18. updCriticalValues,
    19. queryExamInfo,
    20. printFilm,
    21. downloadReport,
    22. updateReportStatus,
    23. queryFilmPrintStatus,
    24. }
    25. public class WSHelper
    26. {
    27. ///
    28. /// 输出的dll文件名称
    29. ///
    30. private static string m_OutputDllFilename;
    31. ///
    32. /// WebService代理类名称
    33. ///
    34. private static string m_ProxyClassName;
    35. ///
    36. /// WebService代理类实例
    37. ///
    38. private static object m_ObjInvoke;
    39. ///
    40. /// 接口方法字典
    41. ///
    42. private static Dictionary m_MethodDic = new Dictionary();
    43. ///
    44. /// 创建WebService,生成客户端代理程序集文件
    45. ///
    46. ///
    47. ///
    48. public static bool CreateWebService(out string error)
    49. {
    50. try
    51. {
    52. error = string.Empty;
    53. m_OutputDllFilename = "report.dll";
    54. m_ProxyClassName = "IGEDataServicesService";
    55. string webServiceUrl = "http://127.0.0.1:8080/integration_web/services/GEDataServices?wsdl";
    56. // 如果程序集已存在,直接使用
    57. if (File.Exists(Path.Combine(Environment.CurrentDirectory, m_OutputDllFilename)))
    58. {
    59. BuildMethods();
    60. return true;
    61. }
    62. //使用 WebClient 下载 WSDL 信息。
    63. WebClient web = new WebClient();
    64. Stream stream = web.OpenRead(webServiceUrl);
    65. //创建和格式化 WSDL 文档。
    66. if (stream != null)
    67. {
    68. // 格式化WSDL
    69. ServiceDescription description = ServiceDescription.Read(stream);
    70. // 创建客户端代理类。
    71. ServiceDescriptionImporter importer = new ServiceDescriptionImporter
    72. {
    73. ProtocolName = "Soap",
    74. Style = ServiceDescriptionImportStyle.Client,
    75. CodeGenerationOptions =
    76. CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync
    77. };
    78. // 添加 WSDL 文档。
    79. importer.AddServiceDescription(description, null, null);
    80. //使用 CodeDom 编译客户端代理类。
    81. CodeNamespace nmspace = new CodeNamespace();
    82. CodeCompileUnit unit = new CodeCompileUnit();
    83. unit.Namespaces.Add(nmspace);
    84. ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit);
    85. CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
    86. CompilerParameters parameter = new CompilerParameters
    87. {
    88. GenerateExecutable = false,
    89. // 指定输出dll文件名。
    90. OutputAssembly = m_OutputDllFilename
    91. };
    92. parameter.ReferencedAssemblies.Add("System.dll");
    93. parameter.ReferencedAssemblies.Add("System.XML.dll");
    94. parameter.ReferencedAssemblies.Add("System.Web.Services.dll");
    95. parameter.ReferencedAssemblies.Add("System.Data.dll");
    96. // 编译输出程序集
    97. CompilerResults result = provider.CompileAssemblyFromDom(parameter, unit);
    98. // 使用 Reflection 调用 WebService。
    99. if (!result.Errors.HasErrors)
    100. {
    101. BuildMethods();
    102. return true;
    103. }
    104. else
    105. {
    106. error = "反射生成dll文件时异常";
    107. }
    108. stream.Close();
    109. stream.Dispose();
    110. }
    111. else
    112. error = "打开WebServiceUrl失败";
    113. }
    114. catch (Exception ex)
    115. {
    116. error = "异常:"+ex.Message;
    117. //Log.WriteLog(error);
    118. }
    119. return false;
    120. }
    121. ///
    122. /// 反射构建Methods
    123. ///
    124. private static void BuildMethods()
    125. {
    126. Assembly asm = Assembly.LoadFrom(m_OutputDllFilename);
    127. Type[] types = asm.GetTypes();
    128. Type asmType = asm.GetType(m_ProxyClassName);
    129. m_ObjInvoke = Activator.CreateInstance(asmType);
    130. var methods = Enum.GetNames(typeof(EMethod)).ToList();
    131. foreach (var item in methods)
    132. {
    133. var methodInfo = asmType.GetMethod(item);
    134. if (methodInfo != null)
    135. {
    136. var method = (EMethod)Enum.Parse(typeof(EMethod), item);
    137. m_MethodDic.Add(method, methodInfo);
    138. }
    139. }
    140. }
    141. ///
    142. /// 获取请求响应
    143. ///
    144. ///
    145. ///
    146. ///
    147. public static string GetResponseString(EMethod method, params object[] para)
    148. {
    149. string result = string.Empty;
    150. try
    151. {
    152. if (m_MethodDic.ContainsKey(method))
    153. {
    154. var temp = m_MethodDic[method].Invoke(m_ObjInvoke, para);
    155. if (temp != null)
    156. result = temp.ToString();
    157. }
    158. }
    159. catch { }
    160. return result;
    161. }
    162. }
    163. }

    调用方式:

    1. textBox1.AppendText("start get\r\n");
    2. string error = "";
    3. string param1 = "ZH230911DR8141";
    4. bool succ = WSHelper.CreateWebService(out error);
    5. textBox1.AppendText("error is:" + error + "\r\n");
    6. textBox1.AppendText("succ is:" + succ + "\r\n");
    7. string result = WSHelper.GetResponseString(EMethod.queryExamInfo, param1);
    8. textBox1.AppendText("result is:" + result + "\r\n");

  • 相关阅读:
    【LeetCode】Day175-解析布尔表达式
    玉米社:SEM对SEO有什么意义?如何兼顾SEM、SEO?
    固定资产管理系统给企业带来的价值?
    分享我做Dotnet9博客网站时积累的一些资料
    C++中函数调用的整个过程内存堆栈分配详解
    springboot+jaspersoft studio6制作报表
    基于SpringBoot招聘管理系统设计和实现(源码+LW+调试文档+讲解等)
    关于#r语言#的问题:有没有随机多属性可接受性分析(SMAA)的R语言代码
    基于SpringBoot的师生共评的作业管理系统设计与实现
    【学习推荐】极客时间-左耳听风专栏
  • 原文地址:https://blog.csdn.net/fanhenghui/article/details/132846597