动态调用WebService
通过添加引用的方式来引用WebService不够灵活,在实际应用中,进行测试和正式切换时比较麻烦
而采取灵活方式来实际WebService引用就要便捷的多
辅助类:
1 using System; 2 using System.ServiceModel; 3 using System.ServiceModel.Channels; 4 using System.Net; 5 using System.Web.Services.Description; 6 using System.CodeDom; 7 using Microsoft.CSharp; 8 using System.CodeDom.Compiler; 9 using System.IO; 10 11 /// <summary> 12 /// Webservice 帮助工具类 13 /// </summary> 14 public static class WebserviceHelper 15 { 16 17 /// <summary> 18 /// 根据 Url 创建 webservice 实例 19 /// </summary> 20 /// <typeparam name="T"></typeparam> 21 /// <param name="url"></param> 22 /// <returns></returns> 23 public static T CreateInstance<T>(string url) 24 { 25 if (url.EndsWith("svc")) 26 { 27 return CreateWCF<T>(url); 28 } 29 30 if (url.EndsWith("asmx")) 31 { 32 return CreateAsmx<T>(url); 33 } 34 35 return default(T); 36 } 37 38 private static T CreateWCF<T>(string url) 39 { 40 BasicHttpBinding basicBinding = new BasicHttpBinding(); 41 CustomBinding binding = new CustomBinding(basicBinding); 42 BindingElement binaryElement = new BinaryMessageEncodingBindingElement(); 43 binding.Elements.Remove(binding.Elements[0]); 44 binding.Elements.Insert(0, binaryElement); 45 46 EndpointAddress endPoint = new EndpointAddress(url); 47 48 T client = (T)Activator.CreateInstance(typeof(T), binding, endPoint); 49 50 return client; 51 } 52 53 private static T CreateAsmx<T>(string url) 54 { 55 BasicHttpBinding basicBinding = new BasicHttpBinding(); 56 basicBinding.MaxBufferSize = int.MaxValue; 57 basicBinding.MaxReceivedMessageSize = int.MaxValue; 58 basicBinding.ReceiveTimeout = TimeSpan.FromMinutes(10); 59 basicBinding.OpenTimeout = TimeSpan.FromMinutes(1); 60 61 CustomBinding binding = new CustomBinding(basicBinding); 62 EndpointAddress endPoint = new EndpointAddress(url); 63 64 T client = (T)Activator.CreateInstance(typeof(T), binding, endPoint); 65 66 return client; 67 } 68 69 #region 动态调用WebService动态调用地址 70 /// < summary> 71 /// 动态调用web服务 72 /// </summary> 73 /// < param name="url">WSDL服务地址</param> 74 /// < param name="methodname">方法名</param> 75 /// < param name="args">参数</param> 76 /// < returns></returns> 77 public static object InvokeWebService(string url, string methodname, object[] args) 78 { 79 return WebserviceHelper.InvokeWebService(url, null, methodname, args); 80 } 81 /// <summary> 82 /// 动态调用web服务 83 /// </summary> 84 /// <param name="url">WSDL服务地址</param> 85 /// <param name="classname">服务接口类名</param> 86 /// <param name="methodname">方法名</param> 87 /// <param name="args">参数值</param> 88 /// <returns></returns> 89 public static object InvokeWebService(string url, string classname, string methodname, object[] args) 90 { 91 92 string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling"; 93 if ((classname == null) || (classname == "")) 94 { 95 classname = WebserviceHelper.GetWsClassName(url); 96 } 97 try 98 { 99 100 //获取WSDL 101 WebClient wc = new WebClient(); 102 Stream stream = wc.OpenRead(url + "?WSDL"); 103 ServiceDescription sd = ServiceDescription.Read(stream); 104 //注意classname一定要赋值获取 105 classname = sd.Services[0].Name; 106 107 ServiceDescriptionImporter sdi = new ServiceDescriptionImporter(); 108 sdi.AddServiceDescription(sd, "", ""); 109 CodeNamespace cn = new CodeNamespace(@namespace); 110 111 //生成客户端代理类代码 112 CodeCompileUnit ccu = new CodeCompileUnit(); 113 ccu.Namespaces.Add(cn); 114 sdi.Import(cn, ccu); 115 CSharpCodeProvider icc = new CSharpCodeProvider(); 116 117 118 //设定编译参数 119 CompilerParameters cplist = new CompilerParameters(); 120 cplist.GenerateExecutable = false; 121 cplist.GenerateInMemory = true; 122 cplist.ReferencedAssemblies.Add("System.dll"); 123 cplist.ReferencedAssemblies.Add("System.XML.dll"); 124 cplist.ReferencedAssemblies.Add("System.Web.Services.dll"); 125 cplist.ReferencedAssemblies.Add("System.Data.dll"); 126 //编译代理类 127 CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu); 128 if (true == cr.Errors.HasErrors) 129 { 130 System.Text.StringBuilder sb = new System.Text.StringBuilder(); 131 foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors) 132 { 133 sb.Append(ce.ToString()); 134 sb.Append(System.Environment.NewLine); 135 } 136 throw new Exception(sb.ToString()); 137 } 138 //生成代理实例,并调用方法 139 System.Reflection.Assembly assembly = cr.CompiledAssembly; 140 Type t = assembly.GetType(@namespace + "." + classname, true, true); 141 object obj = Activator.CreateInstance(t); 142 System.Reflection.MethodInfo mi = t.GetMethod(methodname); 143 return mi.Invoke(obj, args); 144 145 } 146 catch (Exception ex) 147 { 148 throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace)); 149 // return "Error:WebService调用错误!" + ex.Message; 150 } 151 } 152 /// <summary> 153 /// 获取web服务的classname 154 /// </summary> 155 /// <param name="wsUrl"></param> 156 /// <returns></returns> 157 private static string GetWsClassName(string wsUrl) 158 { 159 string[] parts = wsUrl.Split('/'); 160 string[] pps = parts[parts.Length - 1].Split('.'); 161 return pps[0]; 162 } 163 #endregion 164 165 }
调用:
object[] args = new object[2]; args[0] = (""); args[1] = (""); object objReturn = WebserviceHelper.InvokeWebService("url", "hello", args);