C# 动态生成WebService,无需添加引用

2021-05-13 14:28

阅读:608

标签:end   common   classname   append   time   reference   move   channel   name   

C#项目调用WebService是很常见的现象,但一旦修改链接地址就需要重新更新引用很是麻烦,这里跟大家分享一个通过地址,无需添加引用动态生成Webservice的小方法

方法类:

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

方法调用:
技术分享技术分享
 1  /// 
 2         /// 调用操作
 3         /// 
 4         /// 
 5         /// 
 6         private void Operation()
 7         {
 8            #region 动态调用 webservices地址
 9             try
10             {
11                
12                 object[] args = new object[2];
13                 args[0] = ("参数一");
14                 args[1] = ("参数二");
15 
16                 object result = WebServiceHelper.InvokeWebService("http://10.135.10.110:8000/ServiceTest.asmx", "serviceMethod", args);
17                 string message = result.ToString();
18 
19             }
20             catch { }
21             #endregion
22         }
View Code

 

C# 动态生成WebService,无需添加引用

标签:end   common   classname   append   time   reference   move   channel   name   

原文地址:http://www.cnblogs.com/mengfangchao/p/7543660.html


评论


亲,登录后才可以留言!