本文列出了如何在C#下動(dòng)態(tài)調(diào)用Web服務(wù)的3種方法,供大家參考。
我們?cè)陂_(kāi)發(fā)C# WinForm時(shí),有時(shí)會(huì)調(diào)用Web服務(wù),服務(wù)是本地的當(dāng)前好辦,只要在Project中的Web References中引入就可以在代碼中直接創(chuàng)建一個(gè)Web服務(wù)對(duì)象來(lái)引用,其實(shí)其原理是C#幫你自動(dòng)創(chuàng)建客戶端代理類的方式調(diào)用WebService,但如果調(diào)用的服務(wù)是動(dòng)態(tài)的,比如說(shuō)在幾個(gè)IIS中都有相同的一個(gè)服務(wù),在運(yùn)行時(shí)輸入具體的IP才確定調(diào)用哪個(gè)服務(wù),那要怎么樣實(shí)現(xiàn)呢。
C#動(dòng)態(tài)調(diào)用Web服務(wù)方法一: 手動(dòng)的添加一個(gè)Web引用,然后修改下本地的代理類。最后實(shí)現(xiàn)Web Service的URI部署到配置文件里。 具體做法如下:
以下代碼是顯示如何配置動(dòng)態(tài)的Web Service,以服務(wù)單元C(類名為Web_SVSGC)為例:
(1)首先在Web引用中的本地代理類中添加一個(gè)構(gòu)造函數(shù),這個(gè)構(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:///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
-
- '添加一個(gè)帶參數(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可以隨時(shí)修改。)
復(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)用時(shí),根據(jù)配置文件的Url動(dòng)態(tài)的生成Web Service。
復(fù)制 保存
- '要調(diào)用的Web Service的URL
- Dim strWebSvsUrl As String
- '聲明一個(gè)要調(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")
- '生成一個(gè)Web Service實(shí)例
- objSVSGC = New WebSvs_GC.SVSGC (strWebSvsUrl)
- '調(diào)用這個(gè)Web Service里的遠(yuǎn)程方法
- strReturnValue = objSVSGC.HelloWorld()
- Catch ex As Exception
- End Try
C#動(dòng)態(tài)調(diào)用Web服務(wù)方法二:完全動(dòng)態(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
- {
-
-
-
-
-
-
-
-
- public class WebServiceHelper
- {
- #region InvokeWebService
-
-
-
-
-
-
-
- public static object InvokeWebService(string url, string methodname, object[] args)
- {
- return WebServiceHelper.InvokeWebService(url, null, methodname, args);
- }
-
-
-
-
-
-
-
-
-
- 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
- {
-
- 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();
-
-
- 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());
- }
-
-
- 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);
-
-
-
-
-
- }
- 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
- }
- }
返回時(shí)如果不是字符串,即強(qiáng)制轉(zhuǎn)換,如返回是DataSet,則
- string url = "http://www./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#動(dòng)態(tài)調(diào)用Web服務(wù)方法三:URL Behavior 屬性
如果知道服務(wù)的方法和參數(shù),只是調(diào)用的URL網(wǎng)址會(huì)隨時(shí)變化,那么可以手工創(chuàng)建一個(gè)服務(wù),添加上對(duì)應(yīng)的的方法和傳入?yún)?shù),然后引入到項(xiàng)目中,就可以直接開(kāi)發(fā),在創(chuàng)建服務(wù)的實(shí)例化時(shí),才修改對(duì)應(yīng)的URL即可.
例如服務(wù)中有個(gè)方法叫GetTax,那么就可以這樣改:
- GetTax.GetTax GetTax1 = new GetTax.GetTax();
- GetTax1.Url = "http://" + WebIp1 + "/pub_wa_gspsp1/gettax.asmx"; //動(dòng)態(tài)引入服務(wù)器
-
- DataSet DS1 = GetTax1.GetTaxMx(Bm1, OldBz, Fpl, SLx, StaDa, EndDa);