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

C#調(diào)用WebService的方法步驟

 更新時間:2025年03月19日 09:45:22   作者:m0_74823983  
在日常工作中,如果涉及到與第三方進(jìn)行接口對接,有的會使用WebService的方式,這篇文章主要講解在.NET?Framework中如何調(diào)用WebService,感興趣的小伙伴跟著小編一起來看看吧

前言

在日常工作中,如果涉及到與第三方進(jìn)行接口對接,有的會使用WebService的方式,這篇文章主要講解在.NET Framework中如何調(diào)用WebService。

創(chuàng)建WebService

(1)新建項目——模板選擇ASP.NET Web 應(yīng)用程序

在這里插入圖片描述

(2)選擇空項目模板

在這里插入圖片描述

(3)右擊項目-添加-Web服務(wù)(ASMX)

在這里插入圖片描述

(4)新建后會自動生成一個測試服務(wù)HelloWorld并返回執(zhí)行字符串

在這里插入圖片描述

(5)點擊運行,并調(diào)用返回

在這里插入圖片描述

方法一:靜態(tài)引用

這種方式是通過添加靜態(tài)引用的方式調(diào)用WebService

1.首先創(chuàng)建一個Winform程序,右擊引用-添加服務(wù)引用。地址即為 運行的WebService地址,命名空間可自命名

在這里插入圖片描述

2.設(shè)計Winform窗體,可選擇工具箱button調(diào)用,TextBox入?yún)?/p>

在這里插入圖片描述

3.根據(jù)所需,調(diào)用WebService服務(wù)即可拿到返回參數(shù)

在這里插入圖片描述

方法二:動態(tài)調(diào)用

上面使用靜態(tài)引用的方式調(diào)用WebService,但是這種方式有一個缺點:如果發(fā)布的WebService地址改變,那么就要重新添加WebService的引用。如果是現(xiàn)有的WebService發(fā)生了改變,也要更新現(xiàn)有的服務(wù)引用,這需要把代碼放到現(xiàn)場才可以。

使用動態(tài)調(diào)用WebService的方法可以解決該問題。

1.我們在配置文件里面添加配置,把WebService的地址、WebService提供的類名、要調(diào)用的方法名稱,都寫在配置文件里面

在這里插入圖片描述

2.同樣設(shè)計Winform界面,添加按鈕,調(diào)用WebService服務(wù)

添加幫助類

using System;
using System.CodeDom.Compiler;
using System.CodeDom;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using System.Web;
using System.Xml.Serialization;
using System.Web.Caching;
using System.Web.Services.Description;

namespace ApiTest1
{
    internal 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);
        }



        /// <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];
        //}
    }
}

3.動態(tài)調(diào)用WebService代碼:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ApiTest1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_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)建實例
            object o = Activator.CreateInstance(t);
            MethodInfo method = t.GetMethod(methodName);
            // 參數(shù)
            string MsgCode = textBox1.Text;
            string SendXml = textBox2.Text;
            //string UserCode = textBox3.Text;
            object[] args = { MsgCode, SendXml};
            //object[] args = { "動態(tài)調(diào)用WebService" };
            // 調(diào)用訪問,獲取方法返回值
            string value = method.Invoke(o, args).ToString();
            //輸出返回值
            MessageBox.Show($"返回值:{value}");
        }
    }
}

程序運行結(jié)果

在這里插入圖片描述

如果說類名沒有提供,可以根據(jù)url來自動獲取類名:

見幫助類(WebServiceHelper)中GetWsClassName 方法。

到此這篇關(guān)于C#調(diào)用WebService的方法步驟的文章就介紹到這了,更多相關(guān)C#調(diào)用WebService內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • C# 使用WPF 用MediaElement控件實現(xiàn)視頻循環(huán)播放

    C# 使用WPF 用MediaElement控件實現(xiàn)視頻循環(huán)播放

    在WPF里用MediaElement控件,實現(xiàn)一個循環(huán)播放單一視頻的程序,同時可以控制視頻的播放、暫停、停止。這篇文章給大家介紹了C# 使用WPF 用MediaElement控件實現(xiàn)視頻循環(huán)播放,需要的朋友參考下吧
    2018-04-04
  • C#實現(xiàn)綁定Combobox的方法

    C#實現(xiàn)綁定Combobox的方法

    這篇文章主要介紹了C#實現(xiàn)綁定Combobox的方法,涉及Combobox參數(shù)設(shè)置的相關(guān)技巧,具有一定參考借鑒價值,需要的朋友可以參考下
    2015-08-08
  • C#使用for循環(huán)移除HTML標(biāo)記

    C#使用for循環(huán)移除HTML標(biāo)記

    大家在項目開發(fā)階段移除文字中的html標(biāo)記最常用的方法就是使用正則表達(dá)式,但是正則表達(dá)式不能處理所有的html文檔,所以采用迭代方式會更好,下面小編給大家解答下
    2016-08-08
  • C#基于自定義事件EventArgs實現(xiàn)發(fā)布訂閱模式

    C#基于自定義事件EventArgs實現(xiàn)發(fā)布訂閱模式

    這篇文章介紹了C#基于自定義事件EventArgs實現(xiàn)發(fā)布訂閱模式的方法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-05-05
  • C# 無邊框窗體之窗體移動實現(xiàn)代碼

    C# 無邊框窗體之窗體移動實現(xiàn)代碼

    這篇文章介紹了C# 無邊框窗體之窗體移動實現(xiàn)代碼,有需要的朋友可以參考一下
    2013-10-10
  • C#實現(xiàn)表格數(shù)據(jù)轉(zhuǎn)實體的示例代碼

    C#實現(xiàn)表格數(shù)據(jù)轉(zhuǎn)實體的示例代碼

    在實際開發(fā)過程中,特別是接口對接之類的,對于這種需求是屢見不鮮,現(xiàn)在很多在線平臺也都提供了像json轉(zhuǎn)實體、sql轉(zhuǎn)實體等。本文將用C#實現(xiàn)這一功能,需要的可以參考一下
    2022-09-09
  • 手把手教你用c#制作一個小型桌面程序

    手把手教你用c#制作一個小型桌面程序

    本文介紹了使用Visual?Studio創(chuàng)建DLL項目,并通過屬性管理器導(dǎo)入工程屬性表的方法,詳細(xì)闡述了制作Windows動態(tài)庫的步驟,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2024-09-09
  • 輕松學(xué)習(xí)C#的異常處理

    輕松學(xué)習(xí)C#的異常處理

    輕松學(xué)習(xí)C#的異常處理,對C#的異常處理感興趣的朋友可以參考本篇文章,幫助大家更靈活的運用C#的異常處理
    2015-11-11
  • C#中using語句的用法

    C#中using語句的用法

    這篇文章介紹了C#中using語句的用法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-03-03
  • 詳解如何在C#類型系統(tǒng)上實現(xiàn)一個SQL查詢引擎TypedSql

    詳解如何在C#類型系統(tǒng)上實現(xiàn)一個SQL查詢引擎TypedSql

    這篇文章主要為大家詳細(xì)介紹了如何在C#類型系統(tǒng)上實現(xiàn)一個SQL查詢引擎TypedSql,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2025-11-11

最新評論

恩平市| 新安县| 满城县| 平果县| 淮阳县| 攀枝花市| 海安县| 嘉鱼县| 天气| 吉安县| 通海县| 陇西县| 布尔津县| 台南市| 和林格尔县| 宣汉县| 遵义县| 锦屏县| 阳江市| 西华县| 屯门区| 会理县| 台山市| 萨迦县| 武冈市| 福州市| 衡东县| 拉孜县| 维西| 宜阳县| 自贡市| 伊宁市| 上思县| 鄂伦春自治旗| 阜康市| 恭城| 江达县| 桦南县| 越西县| 浦县| 汪清县|