You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

86 lines
3.5 KiB

2 years ago
  1. using Microsoft.CSharp;
  2. using System;
  3. using System.CodeDom;
  4. using System.CodeDom.Compiler;
  5. using System.Net;
  6. using System.Text;
  7. using System.Web.Services.Description;
  8. namespace EasyBL
  9. {
  10. public class WebServiceUtil
  11. {
  12. /// <summary>
  13. /// 实例化WebServices
  14. /// </summary>
  15. /// <param name="url">WebServices地址</param>
  16. /// <param name="methodname">调用的方法</param>
  17. /// <param name="args">把webservices里需要的参数按顺序放到这个object[]里</param>
  18. public static object InvokeWebService(string url, string methodname, object[] args)
  19. {
  20. //这里的namespace是需引用的webservices的命名空间,在这里是写死的,大家可以加一个参数从外面传进来。
  21. var @namespace = "client";
  22. try
  23. {
  24. //获取WSDL
  25. using (var wc = new WebClient())
  26. {
  27. var stream = wc.OpenRead(url + "?WSDL");
  28. var sd = ServiceDescription.Read(stream);
  29. var classname = sd.Services[0].Name;
  30. var sdi = new ServiceDescriptionImporter();
  31. sdi.AddServiceDescription(sd, "", "");
  32. var cn = new CodeNamespace(@namespace);
  33. //生成客户端代理类代码
  34. var ccu = new CodeCompileUnit();
  35. ccu.Namespaces.Add(cn);
  36. sdi.Import(cn, ccu);
  37. using (var csc = new CSharpCodeProvider())
  38. {
  39. #pragma warning disable CS0618 // 类型或成员已过时
  40. var icc = csc.CreateCompiler();
  41. #pragma warning restore CS0618 // 类型或成员已过时
  42. //设定编译参数
  43. #pragma warning disable IDE0017 // 简化对象初始化
  44. var cplist = new CompilerParameters
  45. {
  46. #pragma warning restore IDE0017 // 简化对象初始化
  47. GenerateExecutable = false,
  48. GenerateInMemory = true
  49. };
  50. cplist.ReferencedAssemblies.Add("System.dll");
  51. cplist.ReferencedAssemblies.Add("System.XML.dll");
  52. cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
  53. cplist.ReferencedAssemblies.Add("System.Data.dll");
  54. //编译代理类
  55. var cr = icc.CompileAssemblyFromDom(cplist, ccu);
  56. if (cr.Errors.HasErrors)
  57. {
  58. var sb = new StringBuilder();
  59. foreach (CompilerError ce in cr.Errors)
  60. {
  61. sb.Append(ce.ToString());
  62. sb.Append(Environment.NewLine);
  63. }
  64. throw new Exception(sb.ToString());
  65. }
  66. //生成代理实例,并调用方法
  67. var assembly = cr.CompiledAssembly;
  68. var t = assembly.GetType(@namespace + "." + classname, true, true);
  69. var obj = Activator.CreateInstance(t);
  70. var mi = t.GetMethod(methodname);
  71. return mi.Invoke(obj, args);
  72. }
  73. }
  74. }
  75. catch
  76. {
  77. return null;
  78. }
  79. }
  80. }
  81. }