通过文件反射调用接口
#region 反射自动选择接口地址 /// <summary> /// 缓冲池对象 /// </summary> private static Dictionary<string, ServiceEntity> methodPool = new Dictionary<string, ServiceEntity>(); /// <summary> /// web service 实体/// </summary> private class ServiceEntity { System.Reflection.MethodInfo _method; public System.Reflection.MethodInfo Method { get { return _method; } set { _method = value; } } Type _serviceType; public Type ServiceType { get { return _serviceType; } set { _serviceType = value; } } object _serviceTypeInstance; public object ServiceTypeInstance { get { return _serviceTypeInstance; } set { _serviceTypeInstance = value; } } public ServiceEntity(System.Reflection.MethodInfo method, Type serviceType, object serviceTypeInstance) { this.Method = method; this.ServiceType = serviceType; this.ServiceTypeInstance = serviceTypeInstance; } } /// <summary> /// 根据指定的信息,调用远程WebService方法 /// </summary> /// <param name="url">WebService的http形式的地址</param> /// <param name="namespace">欲调用的WebService的命名空间</param> /// <param name="classname">欲调用的WebService的类名(类名)</param> /// <param name="methodname">欲调用的WebService的方法名</param> /// <param name="args">参数列表</param> /// <returns>WebService的执行结果</returns> /// <remarks> /// 如果调用失败,将会抛出Exception。请调用的时候,适当截获异常。 /// 异常信息可能会发生在两个地方: /// 1、动态构造WebService的时候,CompileAssembly失败。 /// 2、WebService本身执行失败。 /// </remarks> /// <example> /// <code> /// 使用方法 /// object [] mArgs = new object[2]; /// mArgs[0] = "1321321321312"; /// mArgs[1] = null; /// object mReturn = InvokeWebservice("http://localhost:3841/Service1.asmx", "WebService1", "Service1", "HelloWorldRef", mArgs); /// </code> /// </example> public static object InvokeWebservice(string url, string @namespace, string classname, string methodname, object[] args, out string Error) { Error = ""; string serviceKey = String.Format("{0}_{1}_{2}_{3}", url, @namespace, classname, methodname); if (methodPool.ContainsKey(serviceKey)) { if (methodPool[serviceKey].ServiceType != null && methodPool[serviceKey].Method != null) { try { object instance = null; if (methodPool[serviceKey].ServiceTypeInstance != null) instance = methodPool[serviceKey].ServiceTypeInstance; else instance = Activator.CreateInstance(methodPool[serviceKey].ServiceType); return methodPool[serviceKey].Method.Invoke(instance, args); } catch (Exception ex) { throw ex; } } else methodPool.Remove(serviceKey); } try { System.Net.WebClient wc = new System.Net.WebClient(); System.IO.Stream stream = wc.OpenRead(url + "?WSDL"); System.Web.Services.Description.ServiceDescription sd = System.Web.Services.Description.ServiceDescription.Read(stream); System.Web.Services.Description.ServiceDescriptionImporter sdi = new System.Web.Services.Description.ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, "", ""); System.CodeDom.CodeNamespace cn = new System.CodeDom.CodeNamespace(@namespace); System.CodeDom.CodeCompileUnit ccu = new System.CodeDom.CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); Microsoft.CSharp.CSharpCodeProvider csc = new Microsoft.CSharp.CSharpCodeProvider(); System.CodeDom.Compiler.ICodeCompiler icc = csc.CreateCompiler(); System.CodeDom.Compiler.CompilerParameters cplist = new System.CodeDom.Compiler.CompilerParameters(); cplist.GenerateExecutable = false; cplist.GenerateInMemory = true; cplist.ReferencedAssemblies.Add("System.dll"); cplist.ReferencedAssemblies.Add("System.XML.dll"); cplist.ReferencedAssemblies.Add("System.Web.Services.dll"); cplist.ReferencedAssemblies.Add("System.Data.dll"); System.CodeDom.Compiler.CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu); if (true == cr.Errors.HasErrors) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors) { sb.Append(ce.ToString()); sb.Append(System.Environment.NewLine); } throw new Exception(sb.ToString()); } System.Reflection.Assembly assembly = cr.CompiledAssembly; Type t = assembly.GetType(@namespace + "." + classname, true, true); object obj = Activator.CreateInstance(t); System.Reflection.MethodInfo mi = t.GetMethod(methodname); methodPool.Add(serviceKey, new ServiceEntity(mi, t, obj)); return mi.Invoke(obj, args); } catch (NullReferenceException NullEx) { Error = NullEx.ToString(); return null; } catch (Exception Ex) { Error = Ex.Message; return null; } } #endregion
调用方法:
object[] para = new object[2]; para[0] = item.DeviceNo; para[1] = Convert.ToInt32(DeviceType); string _Path = "http://localhost:3841/Service1.asmx"; //写入配置文件
object resultData =InvokeWebservice(_Path, "NameSpace", "Equipment", "DelDevice", para, out Error); string strResultData = resultData == null ? "false" : resultData.ToString();
#region 反射自动选择接口地址 /// <summary> /// 缓冲池对象 /// 2008.7.20 anson /// </summary> private static Dictionary<string, ServiceEntity> methodPool = new Dictionary<string, ServiceEntity>();
/// <summary> /// web service 实体 /// 2008.7.20 anson /// </summary> private class ServiceEntity { System.Reflection.MethodInfo _method; public System.Reflection.MethodInfo Method { get { return _method; } set { _method = value; } }
Type _serviceType; public Type ServiceType { get { return _serviceType; } set { _serviceType = value; } }
object _serviceTypeInstance; public object ServiceTypeInstance { get { return _serviceTypeInstance; } set { _serviceTypeInstance = value; } } public ServiceEntity(System.Reflection.MethodInfo method, Type serviceType, object serviceTypeInstance) { this.Method = method; this.ServiceType = serviceType; this.ServiceTypeInstance = serviceTypeInstance; } }
/// <summary> /// 根据指定的信息,调用远程WebService方法 /// </summary> /// <param name="url">WebService的http形式的地址</param> /// <param name="namespace">欲调用的WebService的命名空间</param> /// <param name="classname">欲调用的WebService的类名(不包括命名空间前缀)</param> /// <param name="methodname">欲调用的WebService的方法名</param> /// <param name="args">参数列表</param> /// <returns>WebService的执行结果</returns> /// <remarks> /// 如果调用失败,将会抛出Exception。请调用的时候,适当截获异常。 /// 异常信息可能会发生在两个地方: /// 1、动态构造WebService的时候,CompileAssembly失败。 /// 2、WebService本身执行失败。 /// </remarks> /// <example> /// <code> /// 使用方法 /// object [] mArgs = new object[2]; /// mArgs[0] = "1321321321312"; /// mArgs[1] = null; /// object mReturn = InvokeWebservice("http://localhost:3841/Service1.asmx", "WebService1", "Service1", "HelloWorldRef", mArgs); /// </code> /// </example> public static object InvokeWebservice(string url, string @namespace, string classname, string methodname, object[] args, out string Error) { Error = ""; string serviceKey = String.Format("{0}_{1}_{2}_{3}", url, @namespace, classname, methodname); if (methodPool.ContainsKey(serviceKey)) { if (methodPool[serviceKey].ServiceType != null && methodPool[serviceKey].Method != null) { try { object instance = null; if (methodPool[serviceKey].ServiceTypeInstance != null) instance = methodPool[serviceKey].ServiceTypeInstance; else instance = Activator.CreateInstance(methodPool[serviceKey].ServiceType); return methodPool[serviceKey].Method.Invoke(instance, args); } catch (Exception ex) { throw ex; } } else methodPool.Remove(serviceKey); }
try { System.Net.WebClient wc = new System.Net.WebClient(); System.IO.Stream stream = wc.OpenRead(url + "?WSDL"); System.Web.Services.Description.ServiceDescription sd = System.Web.Services.Description.ServiceDescription.Read(stream); System.Web.Services.Description.ServiceDescriptionImporter sdi = new System.Web.Services.Description.ServiceDescriptionImporter(); sdi.AddServiceDescription(sd, "", ""); System.CodeDom.CodeNamespace cn = new System.CodeDom.CodeNamespace(@namespace); System.CodeDom.CodeCompileUnit ccu = new System.CodeDom.CodeCompileUnit(); ccu.Namespaces.Add(cn); sdi.Import(cn, ccu); Microsoft.CSharp.CSharpCodeProvider csc = new Microsoft.CSharp.CSharpCodeProvider(); System.CodeDom.Compiler.ICodeCompiler icc = csc.CreateCompiler(); System.CodeDom.Compiler.CompilerParameters cplist = new System.CodeDom.Compiler.CompilerParameters(); cplist.GenerateExecutable = false; cplist.GenerateInMemory = true; cplist.ReferencedAssemblies.Add("System.dll"); cplist.ReferencedAssemblies.Add("System.XML.dll"); cplist.ReferencedAssemblies.Add("System.Web.Services.dll"); cplist.ReferencedAssemblies.Add("System.Data.dll"); System.CodeDom.Compiler.CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu); if (true == cr.Errors.HasErrors) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors) { sb.Append(ce.ToString()); sb.Append(System.Environment.NewLine); } throw new Exception(sb.ToString()); } System.Reflection.Assembly assembly = cr.CompiledAssembly; Type t = assembly.GetType(@namespace + "." + classname, true, true); object obj = Activator.CreateInstance(t); System.Reflection.MethodInfo mi = t.GetMethod(methodname); methodPool.Add(serviceKey, new ServiceEntity(mi, t, obj)); return mi.Invoke(obj, args); } catch (NullReferenceException NullEx) { Error = NullEx.ToString(); return null; } catch (Exception Ex) { Error = Ex.Message; return null; } } #endregion