C#動態調用Web服務的3種方法

我們在開發C# WinForm時,有時會調用Web服務,服務是本地的當前好辦,只要在Project中的Web References中引入就可以在代碼中直接創建一個Web服務對象來引用,其實其原理是C#幫你自動創建客戶端代理類的方式調用WebService,但如果調用的服務是動態的,比如說在幾個IIS中都有相同的一個服務,在運行時輸入具體的IP才確定調用哪個服務,那要怎麼樣實現呢。

C#動態調用Web服務方法一: 手動的添加一個Web引用,然後修改下本地的代理類。最後實現Web Service的URI部署到配置文件裏。 具體做法如下:

以下代碼是顯示如何配置動態的Web Service,以服務單元C(類名爲Web_SVSGC)爲例:

(1)首先在Web引用中的本地代理類中添加一個構造函數,這個構造函數是以Web Service的URL爲參數的重載方法。

複製  保存

  1. Namespace Web_SVSGC  
  2.     '< remarks/> 
  3.     < System.Diagnostics.DebuggerStepThroughAttribute(),  _     System.ComponentModel.DesignerCategoryAttribute("code"),  _     System.Web.Services.WebServiceBindingAttribute(Name:="SVSGCSoap", [Namespace]:="http://tempuri.org/QYJSERVICE/SVSGC"),  _     System.Xml.Serialization.XmlIncludeAttribute(GetType(Attribute))>  _  
  4.     Public Class SVSGC  
  5.         Inherits System.Web.Services.Protocols.SoapHttpClientProtocol  
  6.     '< remarks/> 
  7.         Public Sub New()  
  8.             MyBase.New  
  9.             Me.Url = "http://localhost/QYJSERVICE/WEBSERVICE/SERVICE/SVSGC.asmx" 
  10.         End Sub  
  11.  
  12.         '添加一個帶參數的構造函數。  
  13.         Public Sub New(ByVal strUrl As String)   
  14.             MyBase.New()   
  15.             Me.Url = strUrl   
  16.         End Sub  
  17.  

(2)將Web Service的url配置在調用Web Service的應用程序的配置文件中。(其中的value可以隨時修改。)

複製  保存

  1. < configuration> 
  2.     < appSettings> 
  3.               < add key="SVSGA_URL" value="http://192.168.108.188/ QDN/SERVICE/SVSGA.asmx" QDN/SERVICE/SVSGA.asmx" /> 
  4.     < /appSettings> 
  5. < /configuration>< configuration> 
  6.     < appSettings> 
  7.               < add key="SVSGA_URL" value="http://192.168.108.188/ QDN/SERVICE/SVSGA.asmx" QDN/SERVICE/SVSGA.asmx" /> 
  8.     < /appSettings> 
  9. < /configuration> 

(3)調用時,根據配置文件的Url動態的生成Web Service。

複製  保存       

  1. '要調用的Web Service的URL  
  2.         Dim strWebSvsUrl As String  
  3.         '聲明一個要調用的Web Service  
  4.         Dim objSVSGC As WebSvs_GC. SVSGC  
  5.         '調用Web Service的遠程方法的返回值  
  6.         Dim strReturnValue As String  
  7.         Try  
  8.             '從配置文件中取得Web Service的URL  
  9.             strWebSvsUrl = _   
  10.             System.Configuration.ConfigurationSettings.AppSettings("SVSGC_URL")   
  11.             '生成一個Web Service實例  
  12.             objSVSGC = New WebSvs_GC.SVSGC (strWebSvsUrl)  
  13.             '調用這個Web Service裏的遠程方法  
  14.             strReturnValue = objSVSGC.HelloWorld()  
  15.         Catch ex As Exception  
  16.         End Try 

C#動態調用Web服務方法二:完全動態處理,傳入服務服務網址,方法名和參數即可.

  1. using System;   
  2. using System.Net;   
  3. using System.IO;   
  4. using System.CodeDom;   
  5. using Microsoft.CSharp;   
  6. using System.CodeDom.Compiler;   
  7. using System.Web.Services.Description;   
  8. using System.Web.Services.Protocols;   
  9.  
  10. namespace HB.Common   
  11. {   
  12.     /* 調用方式   
  13.      *   string url = "http://www.webservicex.net/globalweather.asmx" ;   
  14.      *   string[] args = new string[2] ;   
  15.      *   args[0] = "Hangzhou";   
  16.      *   args[1] = "China" ;   
  17.      *   object result = WebServiceHelper.InvokeWebService(url ,"GetWeather" ,args) ;   
  18.      *   Response.Write(result.ToString());   
  19.      */   
  20.     public class WebServiceHelper   
  21.     {   
  22.         #region InvokeWebService   
  23.         /// < summary>   
  24.         /// 動態調用web服務   
  25.         /// < /summary>   
  26.         /// < param name="url">WSDL服務地址< /param>   
  27.         /// < param name="methodname">方法名< /param>   
  28.         /// < param name="args">參數< /param>   
  29.         /// < returns>< /returns>   
  30.         public static object InvokeWebService(string url, string methodname, object[] args)   
  31.         {   
  32.             return WebServiceHelper.InvokeWebService(url, null, methodname, args);   
  33.         }   
  34.  
  35.         /// < summary>   
  36.         /// 動態調用web服務   
  37.         /// < /summary>   
  38.         /// < param name="url">WSDL服務地址< /param>   
  39.         /// < param name="classname">類名< /param>   
  40.         /// < param name="methodname">方法名< /param>   
  41.         /// < param name="args">參數< /param>   
  42.         /// < returns>< /returns>   
  43.         public static object InvokeWebService(string url, string classname, string methodname, object[] args)   
  44.         {   
  45.             string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling";   
  46.             if ((classname == null) || (classname == ""))   
  47.             {   
  48.                 classname = WebServiceHelper.GetWsClassName(url);   
  49.             }   
  50.  
  51.             try   
  52.             {   
  53.                 //獲取WSDL   
  54.                 WebClient wc = new WebClient();   
  55.                 Stream stream = wc.OpenRead(url + "?WSDL");   
  56.                 ServiceDescription sd = ServiceDescription.Read(stream);   
  57.                 ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();   
  58.                 sdi.AddServiceDescription(sd, """");   
  59.                 CodeNamespace cn = new CodeNamespace(@namespace);   
  60.  
  61.                 //生成客戶端代理類代碼   
  62.                 CodeCompileUnit ccu = new CodeCompileUnit();   
  63.                 ccu.Namespaces.Add(cn);   
  64.                 sdi.Import(cn, ccu);   
  65.                 CSharpCodeProvider icc = new CSharpCodeProvider();   
  66.  
  67.                 //設定編譯參數   
  68.                 CompilerParameters cplist = new CompilerParameters();   
  69.                 cplist.GenerateExecutable = false;   
  70.                 cplist.GenerateInMemory = true;   
  71.                 cplist.ReferencedAssemblies.Add("System.dll");   
  72.                 cplist.ReferencedAssemblies.Add("System.XML.dll");   
  73.                 cplist.ReferencedAssemblies.Add("System.Web.Services.dll");   
  74.                 cplist.ReferencedAssemblies.Add("System.Data.dll");   
  75.  
  76.                 //編譯代理類   
  77.                 CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu);   
  78.                 if (true == cr.Errors.HasErrors)   
  79.                 {   
  80.                     System.Text.StringBuilder sb = new System.Text.StringBuilder();   
  81.                     foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)   
  82.                     {   
  83.                         sb.Append(ce.ToString());   
  84.                         sb.Append(System.Environment.NewLine);   
  85.                     }   
  86.                     throw new Exception(sb.ToString());   
  87.                 }   
  88.  
  89.                 //生成代理實例,並調用方法   
  90.                 System.Reflection.Assembly assembly = cr.CompiledAssembly;   
  91.                 Type t = assembly.GetType(@namespace + "." + classname, truetrue);   
  92.                 object obj = Activator.CreateInstance(t);   
  93.                 System.Reflection.MethodInfo mi = t.GetMethod(methodname);   
  94.  
  95.                 return mi.Invoke(obj, args);   
  96.  
  97.                 /*   
  98.                 PropertyInfo propertyInfo = type.GetProperty(propertyname);   
  99.                 return propertyInfo.GetValue(obj, null);   
  100.                 */   
  101.             }   
  102.             catch (Exception ex)   
  103.             {   
  104.                 throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));   
  105.             }   
  106.         }   
  107.  
  108.         private static string GetWsClassName(string wsUrl)   
  109.         {   
  110.             string[] parts = wsUrl.Split('/');   
  111.             string[] pps = parts[parts.Length - 1].Split('.');   
  112.  
  113.             return pps[0];   
  114.         }   
  115.         #endregion   
  116.     }   

返回時如果不是字符串,即強制轉換,如返回是DataSet,則

  1. string url = "http://www.webservicex.net/globalweather.asmx" ;   
  2. string[] args = new string[2] ;   
  3. args[0] = "Hangzhou";   
  4. args[1] = "China" ;   
  5. object result = WebServiceHelper.InvokeWebService(url ,"GetWeather" ,args) ;   
  6. DataSet DSRe=(DataSet)result;  

C#動態調用Web服務方法三:URL Behavior 屬性

如果知道服務的方法和參數,只是調用的URL網址會隨時變化,那麼可以手工創建一個服務,添加上對應的的方法和傳入參數,然後引入到項目中,就可以直接開發,在創建服務的實例化時,才修改對應的URL即可.

例如服務中有個方法叫GetTax,那麼就可以這樣改:

  1. GetTax.GetTax GetTax1 = new GetTax.GetTax();   
  2. GetTax1.Url = "http://" + WebIp1 + "/pub_wa_gspsp1/gettax.asmx";        //動態引入服務器   
  3.                    
  4. DataSet DS1 = GetTax1.GetTaxMx(Bm1, OldBz, Fpl, SLx, StaDa, EndDa);   //調用服務器返回開票數據 
發佈了79 篇原創文章 · 獲贊 8 · 訪問量 22萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章