最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C#調(diào)用WebService的方法介紹

 更新時(shí)間:2022年03月25日 10:47:53   作者:.NET開發(fā)菜鳥  
這篇文章介紹了C#調(diào)用WebService的方法,文中通過示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

一、前言

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

創(chuàng)建好了WebService以后,把WebService部署到IIS上,并確??梢栽L問

二、靜態(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)行程序測(cè)試:

這樣就可以實(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)場(chǎng)才可以。那么有沒有什么方式可以解決這種問題呢?那就是使用動(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)文章

最新評(píng)論

靖边县| 托克逊县| 汾阳市| 徐水县| 崇信县| 临漳县| 永顺县| 项城市| 南丰县| 江西省| 沾化县| 额尔古纳市| 靖远县| 张家口市| 叶城县| 肇庆市| 涟水县| 昔阳县| 德令哈市| 封丘县| 衡阳县| 伊金霍洛旗| 潢川县| 沾益县| 礼泉县| 吉水县| 兰州市| 什邡市| 泸定县| 临夏县| 辽阳市| 丹凤县| 敖汉旗| 黑水县| 新蔡县| 乌兰县| 彰武县| 闽清县| 望江县| 深州市| 广丰县|