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ù)制 保存
- Namespace Web_SVSGC
- '< remarks/>
- < 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))> _
- Public Class SVSGC
- Inherits System.Web.Services.Protocols.SoapHttpClientProtocol
- '< remarks/>
- Public Sub New()
- MyBase.New
- Me.Url = "http://localhost/QYJSERVICE/WEBSERVICE/SERVICE/SVSGC.asmx"
- End Sub
- '添加一個帶參數(shù)的構(gòu)造函數(shù)。
- Public Sub New(ByVal strUrl As String)
- MyBase.New()
- Me.Url = strUrl
- End Sub
(2)將Web Service的url配置在調(diào)用Web Service的應(yīng)用程序的配置文件中。(其中的value可以隨時修改。)
復(fù)制 保存
- < configuration>
- < appSettings>
- < add key="SVSGA_URL" value="http://192.168.108.188/ QDN/SERVICE/SVSGA.asmx" QDN/SERVICE/SVSGA.asmx" />
- < /appSettings>
- < /configuration>< configuration>
- < appSettings>
- < add key="SVSGA_URL" value="http://192.168.108.188/ QDN/SERVICE/SVSGA.asmx" QDN/SERVICE/SVSGA.asmx" />
- < /appSettings>
- < /configuration>
(3)調(diào)用時,根據(jù)配置文件的Url動態(tài)的生成Web Service。
復(fù)制 保存
- '要調(diào)用的Web Service的URL
- Dim strWebSvsUrl As String
- '聲明一個要調(diào)用的Web Service
- Dim objSVSGC As WebSvs_GC. SVSGC
- '調(diào)用Web Service的遠(yuǎn)程方法的返回值
- Dim strReturnValue As String
- Try
- '從配置文件中取得Web Service的URL
- strWebSvsUrl = _
- System.Configuration.ConfigurationSettings.AppSettings("SVSGC_URL")
- '生成一個Web Service實例
- objSVSGC = New WebSvs_GC.SVSGC (strWebSvsUrl)
- '調(diào)用這個Web Service里的遠(yuǎn)程方法
- strReturnValue = objSVSGC.HelloWorld()
- Catch ex As Exception
- End Try
C#動態(tài)調(diào)用Web服務(wù)方法二:完全動態(tài)處理,傳入服務(wù)服務(wù)網(wǎng)址,方法名和參數(shù)即可.
- using System;
- using System.Net;
- using System.IO;
- using System.CodeDom;
- using Microsoft.CSharp;
- using System.CodeDom.Compiler;
- using System.Web.Services.Description;
- using System.Web.Services.Protocols;
- namespace HB.Common
- {
- /* 調(diào)用方式
- * string url = "http://www.webservicex.net/globalweather.asmx" ;
- * string[] args = new string[2] ;
- * args[0] = "Hangzhou";
- * args[1] = "China" ;
- * object result = WebServiceHelper.InvokeWebService(url ,"GetWeather" ,args) ;
- * Response.Write(result.ToString());
- */
- public class WebServiceHelper
- {
- #region InvokeWebService
- /// < summary>
- /// 動態(tài)調(diào)用web服務(wù)
- /// < /summary>
- /// < param name="url">WSDL服務(wù)地址< /param>
- /// < param name="methodname">方法名< /param>
- /// < param name="args">參數(shù)< /param>
- /// < returns>< /returns>
- public static object InvokeWebService(string url, string methodname, object[] args)
- {
- return WebServiceHelper.InvokeWebService(url, null, methodname, args);
- }
- /// < summary>
- /// 動態(tài)調(diào)用web服務(wù)
- /// < /summary>
- /// < param name="url">WSDL服務(wù)地址< /param>
- /// < param name="classname">類名< /param>
- /// < param name="methodname">方法名< /param>
- /// < param name="args">參數(shù)< /param>
- /// < returns>< /returns>
- public static object InvokeWebService(string url, string classname, string methodname, object[] args)
- {
- string @namespace = "EnterpriseServerBase.WebService.DynamicWebCalling";
- if ((classname == null) || (classname == ""))
- {
- classname = WebServiceHelper.GetWsClassName(url);
- }
- try
- {
- //獲取WSDL
- WebClient wc = new WebClient();
- Stream stream = wc.OpenRead(url + "?WSDL");
- ServiceDescription sd = ServiceDescription.Read(stream);
- ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
- sdi.AddServiceDescription(sd, "", "");
- CodeNamespace cn = new CodeNamespace(@namespace);
- //生成客戶端代理類代碼
- CodeCompileUnit ccu = new CodeCompileUnit();
- ccu.Namespaces.Add(cn);
- sdi.Import(cn, ccu);
- CSharpCodeProvider icc = new CSharpCodeProvider();
- //設(shè)定編譯參數(shù)
- CompilerParameters cplist = new CompilerParameters();
- cplist.GenerateExecutable = false;
- cplist.GenerateInMemory = true;
- cplist.ReferencedAssemblies.Add("System.dll");
- cplist.ReferencedAssemblies.Add("System.XML.dll");
- cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
- cplist.ReferencedAssemblies.Add("System.Data.dll");
- //編譯代理類
- CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu);
- if (true == cr.Errors.HasErrors)
- {
- System.Text.StringBuilder sb = new System.Text.StringBuilder();
- foreach (System.CodeDom.Compiler.CompilerError ce in cr.Errors)
- {
- sb.Append(ce.ToString());
- sb.Append(System.Environment.NewLine);
- }
- throw new Exception(sb.ToString());
- }
- //生成代理實例,并調(diào)用方法
- System.Reflection.Assembly assembly = cr.CompiledAssembly;
- Type t = assembly.GetType(@namespace + "." + classname, true, true);
- object obj = Activator.CreateInstance(t);
- System.Reflection.MethodInfo mi = t.GetMethod(methodname);
- return mi.Invoke(obj, args);
- /*
- PropertyInfo propertyInfo = type.GetProperty(propertyname);
- return propertyInfo.GetValue(obj, null);
- */
- }
- catch (Exception ex)
- {
- throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
- }
- }
- private static string GetWsClassName(string wsUrl)
- {
- string[] parts = wsUrl.Split('/');
- string[] pps = parts[parts.Length - 1].Split('.');
- return pps[0];
- }
- #endregion
- }
- }
返回時如果不是字符串,即強(qiáng)制轉(zhuǎn)換,如返回是DataSet,則
- string url = "http://www.webservicex.net/globalweather.asmx" ;
- string[] args = new string[2] ;
- args[0] = "Hangzhou";
- args[1] = "China" ;
- object result = WebServiceHelper.InvokeWebService(url ,"GetWeather" ,args) ;
- 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,那么就可以這樣改:
- GetTax.GetTax GetTax1 = new GetTax.GetTax();
- GetTax1.Url = "http://" + WebIp1 + "/pub_wa_gspsp1/gettax.asmx"; //動態(tài)引入服務(wù)器
- DataSet DS1 = GetTax1.GetTaxMx(Bm1, OldBz, Fpl, SLx, StaDa, EndDa); //調(diào)用服務(wù)器返回開票數(shù)據(jù)
【編輯推薦】