網(wǎng)站首頁 編程語言 正文
一、前言
在日常工作中,如果涉及到與第三方進(jìn)行接口對接,有的會使用WebService的方式,這篇文章主要講解在.NET Framework中如何調(diào)用WebService。首先我們創(chuàng)建一個WebService,里面有兩個方法:一個無參的方法,一個有參的方法:
創(chuàng)建好了WebService以后,把WebService部署到IIS上,并確保可以訪問
二、靜態(tài)引用
這種方式是通過添加靜態(tài)引用的方式調(diào)用WebService。首先創(chuàng)建一個Winform程序,界面上有一個按鈕,點(diǎn)擊按鈕調(diào)用WebService:
然后添加靜態(tài)引用。在要調(diào)用WebService的項(xiàng)目上選擇引用,然后右鍵選擇“添加服務(wù)引用”,如下圖所示:
然后輸入IIS上部署的WebService地址:
最后點(diǎn)擊“確定”按鈕即可完成靜態(tài)引用WebService,添加完成以后的項(xiàng)目結(jié)構(gòu)如下圖所示:
添加完引用以后,就可以編寫代碼了:
/// <summary> /// 靜態(tài)調(diào)用WebService /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btn_Static_Click(object sender, EventArgs e) { // 實(shí)例化類 CallWebService.TestWebSoapClient client = new CallWebService.TestWebSoapClient(); // 調(diào)用無參的HelloWorld方法 string value1= client.HelloWorld(); // 調(diào)用有參的方法 string value2 = client.Test("有參方法"); // 輸出 MessageBox.Show($"無參方法返回值:{value1},有參方法返回值:{value2}"); }
運(yùn)行程序測試:
這樣就可以實(shí)現(xiàn)調(diào)用WebService了。
三、動態(tài)調(diào)用
上面我們說了如何使用靜態(tài)引用的方式調(diào)用WebService,但是這種方式有一個缺點(diǎn):如果發(fā)布的WebService地址改變,那么就要重新添加WebService的引用。如果是現(xiàn)有的WebService發(fā)生了改變,也要更新現(xiàn)有的服務(wù)引用,這需要把代碼放到現(xiàn)場才可以。那么有沒有什么方式可以解決這種問題呢?那就是使用動態(tài)調(diào)用WebService的方法。
我們在配置文件里面添加配置,把WebService的地址、WebService提供的類名、要調(diào)用的方法名稱,都寫在配置文件里面:
<appSettings> <!--WebService地址--> <add key="WebServiceAddress" value="http://localhost:9008/TestWeb.asmx"/> <!--WebService提供的類名--> <add key="ClassName" value="TestWeb"/> <!--WebService方法名--> <add key="MethodName" value="Test"/> <!--存放dll文件的地址--> <add key="FilePath" value="E:\Test"/> </appSettings>
在界面上添加一個按鈕,點(diǎn)擊按鈕可以動態(tài)調(diào)用WebService,新建一個幫助類:
using System; using System.CodeDom; using System.CodeDom.Compiler; using System.IO; using System.Net; using System.Text; using System.Web; using System.Web.Caching; using System.Web.Services.Description; using System.Xml.Serialization; namespace WebServiceDemo { public class WebServiceHelper { /// <summary> /// 生成dll文件保存到本地 /// </summary> /// <param name="url">WebService地址</param> /// <param name="className">類名</param> /// <param name="methodName">方法名</param> /// <param name="filePath">保存dll文件的路徑</param> public static void CreateWebServiceDLL(string url,string className, string methodName,string filePath ) { // 1. 使用 WebClient 下載 WSDL 信息。 WebClient web = new WebClient(); Stream stream = web.OpenRead(url + "?WSDL"); // 2. 創(chuàng)建和格式化 WSDL 文檔。 ServiceDescription description = ServiceDescription.Read(stream); //如果不存在就創(chuàng)建file文件夾 if (Directory.Exists(filePath) == false) { Directory.CreateDirectory(filePath); } if (File.Exists(filePath + className + "_" + methodName + ".dll")) { //判斷緩存是否過期 var cachevalue = HttpRuntime.Cache.Get(className + "_" + methodName); if (cachevalue == null) { //緩存過期刪除dll File.Delete(filePath + className + "_" + methodName + ".dll"); } else { // 如果緩存沒有過期直接返回 return; } } // 3. 創(chuàng)建客戶端代理代理類。 ServiceDescriptionImporter importer = new ServiceDescriptionImporter(); // 指定訪問協(xié)議。 importer.ProtocolName = "Soap"; // 生成客戶端代理。 importer.Style = ServiceDescriptionImportStyle.Client; importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync; // 添加 WSDL 文檔。 importer.AddServiceDescription(description, null, null); // 4. 使用 CodeDom 編譯客戶端代理類。 // 為代理類添加命名空間,缺省為全局空間。 CodeNamespace nmspace = new CodeNamespace(); CodeCompileUnit unit = new CodeCompileUnit(); unit.Namespaces.Add(nmspace); ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit); CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"); CompilerParameters parameter = new CompilerParameters(); parameter.GenerateExecutable = false; // 可以指定你所需的任何文件名。 parameter.OutputAssembly = filePath + className + "_" + methodName + ".dll"; parameter.ReferencedAssemblies.Add("System.dll"); parameter.ReferencedAssemblies.Add("System.XML.dll"); parameter.ReferencedAssemblies.Add("System.Web.Services.dll"); parameter.ReferencedAssemblies.Add("System.Data.dll"); // 生成dll文件,并會把WebService信息寫入到dll里面 CompilerResults result = provider.CompileAssemblyFromDom(parameter, unit); if (result.Errors.HasErrors) { // 顯示編譯錯誤信息 System.Text.StringBuilder sb = new StringBuilder(); foreach (CompilerError ce in result.Errors) { sb.Append(ce.ToString()); sb.Append(System.Environment.NewLine); } throw new Exception(sb.ToString()); } //記錄緩存 var objCache = HttpRuntime.Cache; // 緩存信息寫入dll文件 objCache.Insert(className + "_" + methodName, "1", null, DateTime.Now.AddMinutes(5), TimeSpan.Zero, CacheItemPriority.High, null); } } }
動態(tài)調(diào)用WebService代碼:
/// <summary> /// 動態(tài)調(diào)用WebService /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btn_Dynamic_Click(object sender, EventArgs e) { // 讀取配置文件,獲取配置信息 string url = ConfigurationManager.AppSettings["WebServiceAddress"]; string className = ConfigurationManager.AppSettings["ClassName"]; string methodName = ConfigurationManager.AppSettings["MethodName"]; string filePath = ConfigurationManager.AppSettings["FilePath"]; // 調(diào)用WebServiceHelper WebServiceHelper.CreateWebServiceDLL(url, className, methodName, filePath); // 讀取dll內(nèi)容 byte[] filedata = File.ReadAllBytes(filePath + className + "_" + methodName + ".dll"); // 加載程序集信息 Assembly asm = Assembly.Load(filedata); Type t = asm.GetType(className); // 創(chuàng)建實(shí)例 object o = Activator.CreateInstance(t); MethodInfo method = t.GetMethod(methodName); // 參數(shù) object[] args = {"動態(tài)調(diào)用WebService" }; // 調(diào)用訪問,獲取方法返回值 string value = method.Invoke(o, args).ToString(); //輸出返回值 MessageBox.Show($"返回值:{value}"); }
程序運(yùn)行結(jié)果:
如果說類名沒有提供,可以根據(jù)url來自動獲取類名:
/// <summary> /// 根據(jù)WebService的url地址獲取className /// </summary> /// <param name="wsUrl">WebService的url地址</param> /// <returns></returns> private string GetWsClassName(string wsUrl) { string[] parts = wsUrl.Split('/'); string[] pps = parts[parts.Length - 1].Split('.'); return pps[0]; }
原文鏈接:https://www.cnblogs.com/dotnet261010/p/12461930.html
相關(guān)推薦
- 2022-06-21 Android實(shí)現(xiàn)登陸界面的記住密碼功能_Android
- 2022-09-14 jQuery實(shí)現(xiàn)簡單計算器功能_jquery
- 2022-07-18 SQL?Server中實(shí)現(xiàn)錯誤處理_MsSql
- 2024-04-03 mybatis(mybatis-plus)分頁失效原因
- 2023-07-07 Linux服務(wù)器zip安裝,及壓縮解壓
- 2022-08-18 Android?Canva實(shí)現(xiàn)漸變進(jìn)度條_Android
- 2022-12-07 一文帶你搞懂C語言動態(tài)內(nèi)存管理_C 語言
- 2022-03-29 python中format函數(shù)與round函數(shù)的區(qū)別_python
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支