在C#中動態(tài)調(diào)用WebService
通常我們在程序中需要調(diào)用WebService時,都是通過“添加Web引用”,讓VS.NET環(huán)境來為我們生成服務代理,然后調(diào)用對應的Web服務。這樣是使工作簡單了,但是卻和提供Web服務的URL、方法名、參數(shù)綁定在一起了,這是VS.NET自動為我們生成Web服務代理的限制。如果哪一天發(fā)布Web服務的URL改變了,則我們需要重新讓VS.NET生成代理,并重新編譯。在某些情況下,這可能是不能忍受的,我們需要C#中動態(tài)調(diào)用WebService的能力。比如我們可以把Web服務的URL保存在配置文件中,這樣,當服務URL改變時,只需要修改配置文件就可以了。
說了這么多,實際上我們要實現(xiàn)這樣的功能:
- public static object InvokeWebService(string url,
- string methodname, object[] args)
其中,url是Web服務的地址,methodname是要調(diào)用服務方法名,args是要調(diào)用Web服務所需的參數(shù),返回值就是web服務返回的結(jié)果了。
要實現(xiàn)這樣的功能,你需要這幾個方面的技能:反射、CodeDom、編程使用C#編譯器、WebService。在了解這些知識后,就可以容易的實現(xiàn)web服務的動態(tài)調(diào)用了:
- usingSystem.CodeDom.Compiler;
- usingSystem;
- usingSystem.Net;
- usingSystem.CodeDom;
- usingMicrosoft.CSharp;
- usingSystem.IO;
- usingSystem.Web.Services.Description;
- usingSystem.Collections.Generic;
- usingSystem.Reflection;
- namespacecjl.WebServices
- {
- publicclassDynamicWebServices
- {
- staticSortedList〈string,Type〉_typeList=
- newSortedList〈string,Type〉();
- #regionInvokeWebService
- staticstringGetCacheKey(stringurl,
- stringclassName)
- {
- returnurl.ToLower()+className;
- }
- staticTypeGetTypeFromCache(stringurl,
- stringclassName)
- {
- stringkey=GetCacheKey(url,className);
- foreach(KeyValuePair〈string,Type〉
- pairin_typeList)
- {
- if(key==pair.Key)
- {
- returnpair.Value;
- }
- }
- returnnull;
- }
- staticTypeGetTypeFromWebService
- (stringurl,stringclassName)
- {
- string@namespace="EnterpriseServerBase.
- WebService.DynamicWebCalling";
- if((className==null)||(className==""))
- {
- className=GetWsClassName(url);
- }
- //獲取WSDL
- WebClientwc=newWebClient();
- Streamstream=wc.OpenRead(url+"?WSDL");
- ServiceDescriptionsd=ServiceDescription.
- Read(stream);
- ServiceDescriptionImportersdi=
- newServiceDescriptionImporter();
- sdi.AddServiceDescription(sd,"","");
- CodeNamespacecn=newCodeNamespace
- (@namespace);
- //生成客戶端代理類代碼
- CodeCompileUnitccu=newCodeCompileUnit();
- ccu.Namespaces.Add(cn);
- sdi.Import(cn,ccu);
- CSharpCodeProvidercsc=newCSharpCodeProvider();
- ICodeCompilericc=csc.CreateCompiler();
- //設定編譯參數(shù)
- CompilerParameterscplist=newCompilerParameters();
- 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");
- //編譯代理類
- CompilerResultscr=
- icc.CompileAssemblyFromDom(cplist,ccu);
- if(true==cr.Errors.HasErrors)
- {
- System.Text.StringBuildersb=
- newSystem.Text.StringBuilder();
- foreach(System.CodeDom.Compiler.
- CompilerErrorceincr.Errors)
- {
- sb.Append(ce.ToString());
- sb.Append(System.Environment.NewLine);
- }
- thrownewException(sb.ToString());
- }
- //生成代理實例,并調(diào)用方法
- System.Reflection.Assemblyassembly=
- cr.CompiledAssembly;
- Typet=assembly.GetType(@namespace+".
- "+className,true,true);
- returnt;
- }
- //動態(tài)調(diào)用web服務
- publicstaticobjectInvokeWebService
- (stringurl,stringmethodName,object[]args)
- {
- returnInvokeWebService(url,null,
- methodName,args);
- }
- publicstaticobjectInvokeWebService(stringurl,
- stringclassName,stringmethodName,object[]args)
- {
- try
- {
- Typet=GetTypeFromCache(url,className);
- if(t==null)
- {
- t=GetTypeFromWebService(url,className);
- //添加到緩沖中
- stringkey=GetCacheKey(url,className);
- _typeList.Add(key,t);
- }
- objectobj=Activator.CreateInstance(t);
- MethodInfomi=t.GetMethod(methodName);
- returnmi.Invoke(obj,args);
- }
- catch(Exceptionex)
- {
- thrownewException(ex.InnerException.Message,
- newException(ex.InnerException.StackTrace));
- }
- }
- privatestaticstringGetWsClassName(stringwsUrl)
- {
- string[]parts=wsUrl.Split('/');
- string[]pps=parts[parts.Length-1].Split('.');
- returnpps[0];
- }
- #endregion
- }
- }
上面的注釋已經(jīng)很好的說明了各代碼段的功能,下面給個例子看看,這個例子是通過訪問http://www.webservicex.net/globalweather.asmx服務來獲取各大城市的天氣狀況。
- string url = "http://www.webservicex.
- net/globalweather.asmx";
- string[] args = new string[2];
- args[0] = this.textBox_CityName.Text;
- args[1] = "China";
- object result = WebServiceHelper.
- InvokeWebService(url, "GetWeather", args);
- this.label_Result.Text = result.ToString();
上述的例子中,調(diào)用web服務使用了兩個參數(shù),***個是城市的名字,第二個是國家的名字,Web服務返回的是XML文檔,可以從其中解析出溫度、風力等天氣情況。
***說一下,C#雖然仍屬于靜態(tài)語言之列,但是其動態(tài)能力也是很強大的,不信,你可以看看Spring.net的AOP實現(xiàn),這種“無侵入”的AOP實現(xiàn)比通常的.NET聲明式AOP實現(xiàn)(一般是通過AOP Attribute)要漂亮的多。
【編輯推薦】