自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

C#動態(tài)調(diào)用Web服務(wù)的3種方法

開發(fā) 后端
本文列出了如何在C#下動態(tài)調(diào)用Web服務(wù)的3種方法,供大家參考。

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

C#動態(tài)調(diào)用Web服務(wù)方法一: 手動的添加一個Web引用,然后修改下本地的代理類。***實現(xiàn)Web Service的URI部署到配置文件里。 具體做法如下:

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

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

復(fù)制  保存

  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.         '添加一個帶參數(shù)的構(gòu)造函數(shù)。  
  13.         Public Sub New(ByVal strUrl As String)   
  14.             MyBase.New()   
  15.             Me.Url = strUrl   
  16.         End Sub  
  17.  

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

復(fù)制  保存

  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)調(diào)用時,根據(jù)配置文件的Url動態(tài)的生成Web Service。

復(fù)制  保存       

  1. '要調(diào)用的Web Service的URL  
  2.         Dim strWebSvsUrl As String  
  3.         '聲明一個要調(diào)用的Web Service  
  4.         Dim objSVSGC As WebSvs_GC. SVSGC  
  5.         '調(diào)用Web Service的遠(yuǎn)程方法的返回值  
  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.             '調(diào)用這個Web Service里的遠(yuǎn)程方法  
  14.             strReturnValue = objSVSGC.HelloWorld()  
  15.         Catch ex As Exception  
  16.         End Try 

C#動態(tài)調(diào)用Web服務(wù)方法二:完全動態(tài)處理,傳入服務(wù)服務(wù)網(wǎng)址,方法名和參數(shù)即可.

  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.     /* 調(diào)用方式   
  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.         /// 動態(tài)調(diào)用web服務(wù)   
  25.         /// < /summary>   
  26.         /// < param name="url">WSDL服務(wù)地址< /param>   
  27.         /// < param name="methodname">方法名< /param>   
  28.         /// < param name="args">參數(shù)< /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.         /// 動態(tài)調(diào)用web服務(wù)   
  37.         /// < /summary>   
  38.         /// < param name="url">WSDL服務(wù)地址< /param>   
  39.         /// < param name="classname">類名< /param>   
  40.         /// < param name="methodname">方法名< /param>   
  41.         /// < param name="args">參數(shù)< /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.                 //設(shè)定編譯參數(shù)   
  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.                 //生成代理實例,并調(diào)用方法   
  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.     }   

返回時如果不是字符串,即強(qiáng)制轉(zhuǎn)換,如返回是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#動態(tài)調(diào)用Web服務(wù)方法三:URL Behavior 屬性

如果知道服務(wù)的方法和參數(shù),只是調(diào)用的URL網(wǎng)址會隨時變化,那么可以手工創(chuàng)建一個服務(wù),添加上對應(yīng)的的方法和傳入?yún)?shù),然后引入到項目中,就可以直接開發(fā),在創(chuàng)建服務(wù)的實例化時,才修改對應(yīng)的URL即可.

例如服務(wù)中有個方法叫GetTax,那么就可以這樣改:

  1. GetTax.GetTax GetTax1 = new GetTax.GetTax();   
  2. GetTax1.Url = "http://" + WebIp1 + "/pub_wa_gspsp1/gettax.asmx";        //動態(tài)引入服務(wù)器   
  3.                    
  4. DataSet DS1 = GetTax1.GetTaxMx(Bm1, OldBz, Fpl, SLx, StaDa, EndDa);   //調(diào)用服務(wù)器返回開票數(shù)據(jù) 

【編輯推薦】

  1. 關(guān)于C#知識點總結(jié)
  2. C#開發(fā)和使用中的33個技巧
  3. SQL Server存儲過程介紹
  4. C#下SQL Server 2008表類型參數(shù)傳遞
  5. C#向SQL Server中插入記錄時的問題
責(zé)任編輯:book05 來源: 博客園
相關(guān)推薦

2009-08-11 11:07:49

Java調(diào)用C# we

2009-09-17 16:55:58

C#組件設(shè)計

2009-08-28 16:06:57

C#獲取當(dāng)前路徑方法

2009-07-30 16:27:33

C#比較時間

2009-08-07 13:24:35

C#獲取相對路徑

2011-02-21 16:11:45

C#.NET.NET framew

2009-08-05 16:29:18

C#調(diào)用C++動態(tài)鏈接

2009-08-03 12:57:27

C#調(diào)用DLL

2009-08-31 09:19:31

c#隱藏窗口

2009-08-03 17:53:11

XML數(shù)據(jù)

2009-08-31 18:05:14

C#調(diào)用WalkTre

2009-08-31 16:33:28

C#調(diào)用Dispose

2009-09-17 18:07:22

C#動態(tài)數(shù)組

2009-08-11 14:26:56

C#動態(tài)調(diào)用WebSe

2009-08-05 13:34:18

C#日期相減

2013-02-22 09:54:15

C#Excel讀取Excel

2009-09-01 11:04:59

C#調(diào)用擴(kuò)展方法

2009-10-28 18:00:34

Visual C#數(shù)據(jù)

2009-08-07 16:43:44

C#調(diào)用Windows

2023-08-02 10:10:00

C#C++
點贊
收藏

51CTO技術(shù)棧公眾號