WebService的使用

一、寫一個webService(添加一個web服務)
在當前的網站上 右擊-添加-新建項-web服務

而後在生成的類中添加調用的方法,如這裏在WebService測試.asmx中添加一個test方法web

 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     /// <summary>
10     /// WebService測試 的摘要說明
11     /// </summary>
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.WebService
18     {
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地址瀏覽器

如:http://localhost:46391/WebService測試.asmxide

可看到兩個方法,一個是HelloWorld,另外一個是剛纔新建的test方法。測試

 

 

點擊test能夠進行測試網站

 

 

2、調用webService(添加服務引用)ui

web項目中 右擊-添加服務引用this

地址欄 中輸入webService地址,如上面的webService應輸入http://localhost:46391/WebService測試.asmxurl

而後點轉到,可搜索出對應的webService服務。spa

 

而後,再須要建立一個serviceClient,來調用webService方法(這裏用winform程序簡單寫個按鈕點擊調用)代理

 

 

private void button1_Click(object sender, EventArgs e)
         {
            ServiceReference2.WebService測試SoapClient service new ServiceReference2.WebService測試SoapClient();
            int sum = service.test(112);
            MessageBox.Show(sum.ToString());
         }

 

3動態調用webservice

 

封裝一個WebServiceHelpel類,方便調用

 

 1 public class WebServiceHelper
 2     {
 3         /// <summary>
 4         /// 調用WebService
 5         /// </summary>
 6         /// <param name="wsUrl">WebService地址</param>
 7         /// <param name="methodName">方法名稱</param>
 8         /// <param name="args">參數列表</param>
 9         /// <returns></returns>
10         public static object InvokeWebService(string wsUrl, string methodName, params object[] args)
11         {
12             return InvokeWebService(wsUrl, null, methodName, args);
13         }
14         /// <summary>
15         /// 調用WebService
16         /// </summary>
17         /// <param name="wsUrl">WebService地址</param>
18         /// <param name="className">類名</param>
19         /// <param name="methodName">方法名稱</param>
20         /// <param name="args">參數列表</param>
21         /// <returns></returns>
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.DynamicWebCalling
25             if (string.IsNullOrEmpty(className))
26             {
27                 className = GetWsClassName(wsUrl);
28             }
29             try
30             {
31                 //獲取WSDL
32                 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 /// <summary>
  2     /// Web Service服務類
  3     /// </summary>
  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         /// <summary>
 18         /// 動態調用web服務(含有SoapHeader)
 19         /// </summary>
 20         /// <param name="url"></param>
 21         /// <param name="methodname"></param>
 22         /// <param name="soapHeader"></param>
 23         /// <param name="args"></param>
 24         /// <returns></returns>
 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<string, object> 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                 #endregion
112 
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         /// <summary>  
144         /// 構建SOAP頭,用於SoapHeader驗證  
145         /// </summary>  
146         public class SoapHeader
147         {
148             /// <summary>  
149             /// 構造一個SOAP頭  
150             /// </summary>  
151             public SoapHeader()
152             {
153                 this.Properties = new Dictionary<string, object>();
154             }
155             /// <summary>  
156             /// 構造一個SOAP頭  
157             /// </summary>  
158             /// <param name="className">SOAP頭的類名</param>  
159             public SoapHeader(string className)
160             {
161                 this.ClassName = className;
162                 this.Properties = new Dictionary<string, object>();
163             }
164             /// <summary>  
165             /// 構造一個SOAP頭  
166             /// </summary>  
167             /// <param name="className">SOAP頭的類名</param>  
168             /// <param name="properties">SOAP頭的類屬性名及屬性值</param>  
169             public SoapHeader(string className, Dictionary<string, object> properties)
170             {
171                 this.ClassName = className;
172                 this.Properties = properties;
173             }
174             /// <summary>  
175             /// SOAP頭的類名  
176             /// </summary>  
177             public string ClassName { get; set; }
178             /// <summary>  
179             /// SOAP頭的類屬性名及屬性值  
180             /// </summary>  
181             public Dictionary<string, object> Properties { get; set; }
182             /// <summary>  
183             /// 爲SOAP頭增長一個屬性及值  
184             /// </summary>  
185             /// <param name="name">SOAP頭的類屬性名</param>  
186             /// <param name="value">SOAP頭的類屬性值</param>  
187             public void AddProperty(string name, object value)
188             {
189                 if (this.Properties == null)
190                 {
191                     this.Properties = new Dictionary<string, object>();
192                 }
193                 Properties.Add(name, value);
194             }
195         }
196     }
相關文章
相關標籤/搜索