C#調(diào)用WebService的方法介紹
一、前言
在日常工作中,如果涉及到與第三方進(jìn)行接口對(duì)接,有的會(huì)使用WebService的方式,這篇文章主要講解在.NET Framework中如何調(diào)用WebService。首先我們創(chuàng)建一個(gè)WebService,里面有兩個(gè)方法:一個(gè)無參的方法,一個(gè)有參的方法:

創(chuàng)建好了WebService以后,把WebService部署到IIS上,并確保可以訪問
二、靜態(tài)引用
這種方式是通過添加靜態(tài)引用的方式調(diào)用WebService。首先創(chuàng)建一個(gè)Winform程序,界面上有一個(gè)按鈕,點(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了。
三、動(dòng)態(tài)調(diào)用
上面我們說了如何使用靜態(tài)引用的方式調(diào)用WebService,但是這種方式有一個(gè)缺點(diǎn):如果發(fā)布的WebService地址改變,那么就要重新添加WebService的引用。如果是現(xiàn)有的WebService發(fā)生了改變,也要更新現(xiàn)有的服務(wù)引用,這需要把代碼放到現(xiàn)場才可以。那么有沒有什么方式可以解決這種問題呢?那就是使用動(dòng)態(tài)調(diào)用WebService的方法。
我們?cè)谂渲梦募锩嫣砑优渲?,把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>在界面上添加一個(gè)按鈕,點(diǎn)擊按鈕可以動(dòng)態(tài)調(diào)用WebService,新建一個(gè)幫助類:
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文件,并會(huì)把WebService信息寫入到dll里面
CompilerResults result = provider.CompileAssemblyFromDom(parameter, unit);
if (result.Errors.HasErrors)
{
// 顯示編譯錯(cuò)誤信息
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);
}
}
}動(dòng)態(tài)調(diào)用WebService代碼:
/// <summary>
/// 動(dòng)態(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 = {"動(dòng)態(tài)調(diào)用WebService" };
// 調(diào)用訪問,獲取方法返回值
string value = method.Invoke(o, args).ToString();
//輸出返回值
MessageBox.Show($"返回值:{value}");
}程序運(yùn)行結(jié)果:

如果說類名沒有提供,可以根據(jù)url來自動(dòng)獲取類名:
/// <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];
}到此這篇關(guān)于C#調(diào)用WebService的文章就介紹到這了。希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C#調(diào)用halcon實(shí)現(xiàn)使用鼠標(biāo)滾輪對(duì)圖片進(jìn)行縮放顯示
這篇文章主要為大家詳細(xì)介紹了C#如何調(diào)用halcon實(shí)現(xiàn)使用鼠標(biāo)滾輪對(duì)圖片進(jìn)行縮放顯示,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-03-03
C#數(shù)據(jù)結(jié)構(gòu)之單鏈表(LinkList)實(shí)例詳解
這篇文章主要介紹了C#數(shù)據(jù)結(jié)構(gòu)之單鏈表(LinkList)實(shí)現(xiàn)方法,結(jié)合實(shí)例形式較為詳細(xì)的分析了單鏈表的原理、定義與C#具體實(shí)現(xiàn)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-11-11
Unity向量按照某一點(diǎn)進(jìn)行旋轉(zhuǎn)
這篇文章主要為大家詳細(xì)介紹了Unity向量按照某一點(diǎn)進(jìn)行旋轉(zhuǎn),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-01-01

