C#调用WebService的方法

打印 上一主题 下一主题

主题 539|帖子 539|积分 1617

一、前言
在日常工作中,假如涉及到与第三方举行接口对接,有的会使用WebService的方式,这篇文章主要讲解在.NET Framework中如何调用WebService。
1.创建WebService
(1)新建项目——模板选择ASP.NET Web 应用程序

(2)选择空项目模板

(3)右击项目-添加-Web服务(ASMX)

(4)新建后会主动天生一个测试服务HelloWorld并返回执行字符串

(5)点击运行,并调用返回

二、方法一:静态引用
这种方式是通过添加静态引用的方式调用WebService
1.首先创建一个Winform程序,右击引用-添加服务引用。地址即为 运行的WebService地址,命名空间可自命名

2.计划Winform窗体,可选择工具箱button调用,TextBox入参

3.根据所需,调用WebService服务即可拿到返回参数

三、动态调用
上面使用静态引用的方式调用WebService,但是这种方式有一个缺点:假如发布的WebService地址改变,那么就要重新添加WebService的引用。假如是现有的WebService发生了改变,也要更新现有的服务引用,这需要把代码放到现场才可以。
使用动态调用WebService的方法可以解决该问题。
1.我们在配置文件里面添加配置,把WebService的地址、WebService提供的类名、要调用的方法名称,都写在配置文件里面

2.同样计划Winform界面,添加按钮,调用WebService服务
添加帮助类
  1. using System;
  2. using System.CodeDom.Compiler;
  3. using System.CodeDom;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. using System.Xml.Serialization;
  11. using System.Web;
  12. using System.Xml.Serialization;
  13. using System.Web.Caching;
  14. using System.Web.Services.Description;
  15. namespace ApiTest1
  16. {
  17.     internal class WebServiceHelper
  18.     {
  19.         /// <summary>
  20.         /// 生成dll文件保存到本地
  21.         /// </summary>
  22.         /// <param name="url">WebService地址</param>
  23.         /// <param name="className">类名</param>
  24.         /// <param name="methodName">方法名</param>
  25.         /// <param name="filePath">保存dll文件的路径</param>
  26.         public static void CreateWebServiceDLL(string url, string className, string methodName, string filePath)
  27.         {
  28.             // 1. 使用 WebClient 下载 WSDL 信息。
  29.             WebClient web = new WebClient();
  30.             Stream stream = web.OpenRead(url + "?WSDL");
  31.             // 2. 创建和格式化 WSDL 文档。
  32.             ServiceDescription description = ServiceDescription.Read(stream);
  33.             //如果不存在就创建file文件夹
  34.             if (Directory.Exists(filePath) == false)
  35.             {
  36.                 Directory.CreateDirectory(filePath);
  37.             }
  38.             if (File.Exists(filePath + className + "_" + methodName + ".dll"))
  39.             {
  40.                 //判断缓存是否过期
  41.                 var cachevalue = HttpRuntime.Cache.Get(className + "_" + methodName);
  42.                 if (cachevalue == null)
  43.                 {
  44.                     //缓存过期删除dll
  45.                     File.Delete(filePath + className + "_" + methodName + ".dll");
  46.                 }
  47.                 else
  48.                 {
  49.                     // 如果缓存没有过期直接返回
  50.                     return;
  51.                 }
  52.             }
  53.             // 3. 创建客户端代理代理类。
  54.             ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
  55.             // 指定访问协议。
  56.             importer.ProtocolName = "Soap";
  57.             // 生成客户端代理。
  58.             importer.Style = ServiceDescriptionImportStyle.Client;
  59.             importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync;
  60.             // 添加 WSDL 文档。
  61.             importer.AddServiceDescription(description, null, null);
  62.             // 4. 使用 CodeDom 编译客户端代理类。
  63.             // 为代理类添加命名空间,缺省为全局空间。
  64.             CodeNamespace nmspace = new CodeNamespace();
  65.             CodeCompileUnit unit = new CodeCompileUnit();
  66.             unit.Namespaces.Add(nmspace);
  67.             ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit);
  68.             CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
  69.             CompilerParameters parameter = new CompilerParameters();
  70.             parameter.GenerateExecutable = false;
  71.             // 可以指定你所需的任何文件名。
  72.             parameter.OutputAssembly = filePath + className + "_" + methodName + ".dll";
  73.             parameter.ReferencedAssemblies.Add("System.dll");
  74.             parameter.ReferencedAssemblies.Add("System.XML.dll");
  75.             parameter.ReferencedAssemblies.Add("System.Web.Services.dll");
  76.             parameter.ReferencedAssemblies.Add("System.Data.dll");
  77.             // 生成dll文件,并会把WebService信息写入到dll里面
  78.             CompilerResults result = provider.CompileAssemblyFromDom(parameter, unit);
  79.             if (result.Errors.HasErrors)
  80.             {
  81.                 // 显示编译错误信息
  82.                 System.Text.StringBuilder sb = new StringBuilder();
  83.                 foreach (CompilerError ce in result.Errors)
  84.                 {
  85.                     sb.Append(ce.ToString());
  86.                     sb.Append(System.Environment.NewLine);
  87.                 }
  88.                 throw new Exception(sb.ToString());
  89.             }
  90.             //记录缓存
  91.             var objCache = HttpRuntime.Cache;
  92.             // 缓存信息写入dll文件
  93.             objCache.Insert(className + "_" + methodName, "1", null, DateTime.Now.AddMinutes(5), TimeSpan.Zero, CacheItemPriority.High, null);
  94.         }
  95.         /// <summary>
  96.         /// 根据WebService的url地址获取className
  97.         /// </summary>
  98.         /// <param name="wsUrl">WebService的url地址</param>
  99.         /// <returns></returns>
  100.         //private string GetWsClassName(string wsUrl)
  101.         //{
  102.         //    string[] parts = wsUrl.Split('/');
  103.         //    string[] pps = parts[parts.Length - 1].Split('.');
  104.         //    return pps[0];
  105.         //}
  106.     }
  107. }
复制代码
3.动态调用WebService代码:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Configuration;
  5. using System.Data;
  6. using System.Drawing;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Reflection;
  10. using System.Text;
  11. using System.Threading.Tasks;
  12. using System.Windows.Forms;
  13. namespace ApiTest1
  14. {
  15.     public partial class Form1 : Form
  16.     {
  17.         public Form1()
  18.         {
  19.             InitializeComponent();
  20.         }
  21.         private void button1_Click(object sender, EventArgs e)
  22.         {
  23.             // 读取配置文件,获取配置信息
  24.             string url = ConfigurationManager.AppSettings["WebServiceAddress"];
  25.             string className = ConfigurationManager.AppSettings["ClassName"];
  26.             string methodName = ConfigurationManager.AppSettings["MethodName"];
  27.             string filePath = ConfigurationManager.AppSettings["FilePath"];
  28.             // 调用WebServiceHelper
  29.             WebServiceHelper.CreateWebServiceDLL(url, className, methodName, filePath);
  30.             // 读取dll内容
  31.             byte[] filedata = File.ReadAllBytes(filePath + className + "_" + methodName + ".dll");
  32.             // 加载程序集信息
  33.             Assembly asm = Assembly.Load(filedata);
  34.             Type t = asm.GetType(className);
  35.             // 创建实例
  36.             object o = Activator.CreateInstance(t);
  37.             MethodInfo method = t.GetMethod(methodName);
  38.             // 参数
  39.             string MsgCode = textBox1.Text;
  40.             string SendXml = textBox2.Text;
  41.             //string UserCode = textBox3.Text;
  42.             object[] args = { MsgCode, SendXml};
  43.             //object[] args = { "动态调用WebService" };
  44.             // 调用访问,获取方法返回值
  45.             string value = method.Invoke(o, args).ToString();
  46.             //输出返回值
  47.             MessageBox.Show($"返回值:{value}");
  48.         }
  49.     }
  50. }
复制代码
程序运行结果

假如说类名没有提供,可以根据url来主动获取类名:
见帮助类(WebServiceHelper)中GetWsClassName 方法。
参考链接:C#调用WebService的方法先容

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

不到断气不罢休

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表