1、写一个webService(添加一个web服务)
在当前的网站上 右击-添加-新建项-web服务然后在生成的类中添加调用的方法,如这里在WebService测试.asmx中添加一个test方法1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Web.Services; 6 7 namespace WebApplication1 8 { 9 ///10 /// WebService测试 的摘要说明11 /// 12 [WebService(Namespace = "http://tempuri.org/")]13 [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]14 [System.ComponentModel.ToolboxItem(false)]15 // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。 16 // [System.Web.Script.Services.ScriptService]17 public class WebService测试 : System.Web.Services.WebService18 {19 20 [WebMethod]21 public string HelloWorld()22 {23 return "Hello World";24 }25 [WebMethod]26 public int test(int a,int b)27 {28 return a + b;29 }30 }31 }
可以允许该webService测试,在浏览器中输入webService地址
如:
可看到两个方法,一个是HelloWorld,另一个是刚才新建的test方法。
点击test可以进行测试
2、调用webService(添加服务引用)
在web项目中 右击-添加服务引用
再 地址栏 中输入webService地址,如上面的webService应输入
然后点转到,可搜索出对应的webService服务。
然后,再需要创建一个serviceClient,来调用webService方法(这里用winform程序简单写个按钮点击调用)
private void button1_Click(object sender, EventArgs e) { ServiceReference2.WebService测试SoapClient service = new ServiceReference2.WebService测试SoapClient(); int sum = service.test(1, 12); MessageBox.Show(sum.ToString()); }
3动态调用webservice
封装一个WebServiceHelpel类,方便调用
1 public class WebServiceHelper 2 { 3 ///4 /// 调用WebService 5 /// 6 /// WebService地址 7 /// 方法名称 8 /// 参数列表 9 ///10 public static object InvokeWebService(string wsUrl, string methodName, params object[] args)11 {12 return InvokeWebService(wsUrl, null, methodName, args);13 }14 /// 15 /// 调用WebService16 /// 17 /// WebService地址18 /// 类名19 /// 方法名称20 /// 参数列表21 ///22 public static object InvokeWebService(string wsUrl, string className, string methodName, params object[] args)23 {24 string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling";//ServiceBase.WebService.DynamicWebLoad或EnterpriseServerBase.WebService.DynamicWebCalling25 if (string.IsNullOrEmpty(className))26 {27 className = GetWsClassName(wsUrl);28 }29 try30 {31 //获取WSDL32 WebClient wc = new WebClient();33 Stream stream = wc.OpenRead(wsUrl + "?WSDL");34 ServiceDescription sd = ServiceDescription.Read(stream);35 ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();36 sdi.AddServiceDescription(sd, "", "");37 CodeNamespace cn = new CodeNamespace(@namespace);38 //生成客户端代理类代码39 CodeCompileUnit ccu = new CodeCompileUnit();40 ccu.Namespaces.Add(cn);41 sdi.Import(cn, ccu);42 CSharpCodeProvider csc = new CSharpCodeProvider();43 ICodeCompiler icc = csc.CreateCompiler();44 //设定编译参数45 CompilerParameters cplist = new CompilerParameters();46 cplist.GenerateExecutable = false;47 cplist.GenerateInMemory = true;48 cplist.ReferencedAssemblies.Add("System.dll");49 cplist.ReferencedAssemblies.Add("System.XML.dll");50 cplist.ReferencedAssemblies.Add("System.Web.Services.dll");51 cplist.ReferencedAssemblies.Add("System.Data.dll");52 //编译代理类53 CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu);54 if (true == cr.Errors.HasErrors)55 {56 System.Text.StringBuilder sb = new System.Text.StringBuilder();57 foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)58 {59 sb.Append(ce.ToString());60 sb.Append(System.Environment.NewLine);61 }62 throw new Exception(sb.ToString());63 }64 //生成代理实例,并调用方法65 System.Reflection.Assembly assembly = cr.CompiledAssembly;66 Type t = assembly.GetType(@namespace + "." + className, true, true);67 object obj = Activator.CreateInstance(t);68 System.Reflection.MethodInfo mi = t.GetMethod(methodName);69 return mi.Invoke(obj, args);70 }71 catch (Exception ex)72 {73 throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));74 }75 }76 private static string GetWsClassName(string wsUrl)77 {78 string[] parts = wsUrl.Split('/');79 string[] pps = parts[parts.Length - 1].Split('.');80 return pps[0];81 }82 }
动态调用
static void Main(string[] args) { object o = WebServiceHelper.InvokeWebService("http://localhost:46391/WebService测试.asmx", "test",11,2); Console.WriteLine(o.ToString());//结果输出13 Console.ReadKey(); }
动态调用webService带SoapHeader
1 ///2 /// Web Service服务类 3 /// 4 public class WSHelper 5 { 6 /// < summary> 7 /// 动态调用web服务 (不含有SoapHeader) 8 /// < /summary> 9 /// < param name="url">WSDL服务地址< /param> 10 /// < param name="methodname">方法名< /param> 11 /// < param name="args">参数< /param> 12 /// < returns>< /returns> 13 public static object InvokeWebServiceNoSoapHeader(string url, string methodname, params object[] args) 14 { 15 return WSHelper.InvokeWebService(url, null, methodname, null, args); 16 } 17 ///18 /// 动态调用web服务(含有SoapHeader) 19 /// 20 /// 21 /// 22 /// 23 /// 24 ///25 public static object InvokeWebServiceSoapHeader(string url,string className, string methodname, SoapHeader soapHeader, params object[] args) 26 { 27 28 return WSHelper.InvokeWebService(url, className, methodname, soapHeader, args); 29 } 30 /// < summary> 31 /// 动态调用web服务 32 /// < /summary> 33 /// < param name="url">WSDL服务地址< /param> 34 /// < param name="classname">类名< /param> 35 /// < param name="methodname">方法名< /param> 36 /// < param name="args">参数< /param> 37 /// < returns>< /returns> 38 public static object InvokeWebService(string url, string classname, string methodname, SoapHeader soapHeader, params object[] args) 39 { 40 string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling"; 41 if ((classname == null) || (classname == "")) 42 { 43 classname = WSHelper.GetWsClassName(url); 44 } 45 try 46 { 47 //获取WSDL 48 WebClient wc = new WebClient(); 49 Stream stream = wc.OpenRead(url + "?WSDL"); 50 ServiceDescription sd = ServiceDescription.Read(stream); 51 ServiceDescriptionImporter sdi = new ServiceDescriptionImporter(); 52 sdi.AddServiceDescription(sd, "", ""); 53 CodeNamespace cn = new CodeNamespace(@namespace); 54 55 //生成客户端代理类代码 56 CodeCompileUnit ccu = new CodeCompileUnit(); 57 ccu.Namespaces.Add(cn); 58 sdi.Import(cn, ccu); 59 CSharpCodeProvider icc = new CSharpCodeProvider(); 60 61 //设定编译参数 62 CompilerParameters cplist = new CompilerParameters(); 63 cplist.GenerateExecutable = false; 64 cplist.GenerateInMemory = true; 65 cplist.ReferencedAssemblies.Add("System.dll"); 66 cplist.ReferencedAssemblies.Add("System.XML.dll"); 67 cplist.ReferencedAssemblies.Add("System.Web.Services.dll"); 68 cplist.ReferencedAssemblies.Add("System.Data.dll"); 69 70 //编译代理类 71 CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu); 72 if (cr.Errors.HasErrors) 73 { 74 System.Text.StringBuilder sb = new System.Text.StringBuilder(); 75 foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors) 76 { 77 sb.Append(ce.ToString()); 78 sb.Append(System.Environment.NewLine); 79 } 80 throw new Exception(sb.ToString()); 81 } 82 83 //保存生产的代理类,默认是保存在bin目录下面 84 //TextWriter writer = File.CreateText("MyWebServices.cs"); 85 //icc.GenerateCodeFromCompileUnit(ccu, writer, null); 86 //writer.Flush(); 87 //writer.Close(); 88 89 //生成代理实例 90 System.Reflection.Assembly assembly = cr.CompiledAssembly; 91 Type t = assembly.GetType(@namespace + "." + classname, true, true); 92 object obj = Activator.CreateInstance(t); 93 94 #region 设置SoapHeader 95 FieldInfo client = null; 96 object clientkey = null; 97 if (soapHeader != null) 98 { 99 client = t.GetField(soapHeader.ClassName + "Value");100 //获取客户端验证对象 soap类 101 Type typeClient = assembly.GetType(@namespace + "." + soapHeader.ClassName);102 //为验证对象赋值 soap实例 103 clientkey = Activator.CreateInstance(typeClient);104 //遍历属性 105 foreach (KeyValuePair property in soapHeader.Properties)106 {107 typeClient.GetField(property.Key).SetValue(clientkey, property.Value);108 // typeClient.GetProperty(property.Key).SetValue(clientkey, property.Value, null); 109 }110 }111 #endregion112 113 if (soapHeader != null)114 {115 //设置Soap头 116 client.SetValue(obj, clientkey);117 //pro.SetValue(obj, soapHeader, null); 118 }119 120 //调用指定的方法121 System.Reflection.MethodInfo mi = t.GetMethod(methodname);122 //方法名错误(找不到方法),给出提示123 if (null == mi)124 {125 return "方法名不存在,请检查方法名是否正确!";126 }127 return mi.Invoke(obj, args);128 // PropertyInfo propertyInfo = type.GetProperty(propertyname); 129 //return propertyInfo.GetValue(obj, null); 130 }131 catch (Exception ex)132 {133 throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));134 }135 }136 private static string GetWsClassName(string wsUrl)137 {138 string[] parts = wsUrl.Split('/');139 string[] pps = parts[parts.Length - 1].Split('.');140 return pps[0];141 }142 143 /// 144 /// 构建SOAP头,用于SoapHeader验证 145 /// 146 public class SoapHeader147 {148 ///149 /// 构造一个SOAP头 150 /// 151 public SoapHeader()152 {153 this.Properties = new Dictionary();154 }155 /// 156 /// 构造一个SOAP头 157 /// 158 /// SOAP头的类名 159 public SoapHeader(string className)160 {161 this.ClassName = className;162 this.Properties = new Dictionary();163 }164 /// 165 /// 构造一个SOAP头 166 /// 167 /// SOAP头的类名 168 /// SOAP头的类属性名及属性值 169 public SoapHeader(string className, Dictionaryproperties)170 {171 this.ClassName = className;172 this.Properties = properties;173 }174 /// 175 /// SOAP头的类名 176 /// 177 public string ClassName { get; set; }178 ///179 /// SOAP头的类属性名及属性值 180 /// 181 public DictionaryProperties { get; set; }182 /// 183 /// 为SOAP头增加一个属性及值 184 /// 185 /// SOAP头的类属性名 186 /// SOAP头的类属性值 187 public void AddProperty(string name, object value)188 {189 if (this.Properties == null)190 {191 this.Properties = new Dictionary();192 }193 Properties.Add(name, value);194 }195 }196 }