c#对接webservice接口

方式一:需要填写地址,不能映射每个方法

工具类

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.Web.Services.Description;
using System.Xml.Serialization;
using System.Web;
using System.Web.Caching;namespace ReportTest
{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);// 2. 创建和格式化 WSDL 文档。ServiceDescription description = ServiceDescription.Read(stream);//如果不存在就创建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){//缓存过期删除dllFile.Delete(filePath + className + "_" + methodName + ".dll");}else{// 如果缓存没有过期直接返回return;}}// 3. 创建客户端代理代理类。ServiceDescriptionImporter importer = new ServiceDescriptionImporter();// 指定访问协议。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);}}
}

调用方法:

            // 读取配置文件,获取配置信息string url = "http://127.0.0.1:8080/integration_web/services/GEDataServices?wsdl";string className = "IGEDataServicesService";string methodName = "queryExamInfo";string filePath = "D:/my";// 调用WebServiceHelperWebServiceHelper.CreateWebServiceDLL(url, className, methodName, filePath);// 读取dll内容byte[] filedata = File.ReadAllBytes(filePath + className + "_" + methodName + ".dll");// 加载程序集信息Assembly asm = Assembly.Load(filedata);Type t = asm.GetType(className);// 创建实例object o = Activator.CreateInstance(t);MethodInfo method = t.GetMethod(methodName);// 参数object[] args = { "<?xml version=\"1.0\" encoding=\"GBK\" ?><request><patientid></patientid><accessionid>ZH230911DR8141</accessionid></request>" };// 调用访问,获取方法返回值string result = method.Invoke(o, args).ToString();//输出返回值textBox1.AppendText("result is:" + result + "\r\n");

方式二:需要提前写好方法名,调用简单像调用类方法一样

using System;
using System.CodeDom.Compiler;
using System.CodeDom;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using System.IO;
using System.Web.Services.Description;namespace ReportGetWS
{public enum EMethod{updCriticalValues,queryExamInfo,printFilm,downloadReport,updateReportStatus,queryFilmPrintStatus,}public class WSHelper{/// <summary>/// 输出的dll文件名称/// </summary>private static string m_OutputDllFilename;/// <summary>/// WebService代理类名称/// </summary>private static string m_ProxyClassName;/// <summary>/// WebService代理类实例/// </summary>private static object m_ObjInvoke;/// <summary>/// 接口方法字典/// </summary>private static Dictionary<EMethod, MethodInfo> m_MethodDic = new Dictionary<EMethod, MethodInfo>();/// <summary>/// 创建WebService,生成客户端代理程序集文件/// </summary>/// <param name="error"></param>/// <returns></returns>public static bool CreateWebService(out string error){try{error = string.Empty;m_OutputDllFilename = "report.dll";m_ProxyClassName = "IGEDataServicesService";string webServiceUrl = "http://127.0.0.1:8080/integration_web/services/GEDataServices?wsdl";// 如果程序集已存在,直接使用if (File.Exists(Path.Combine(Environment.CurrentDirectory, m_OutputDllFilename))){BuildMethods();return true;}//使用 WebClient 下载 WSDL 信息。WebClient web = new WebClient();Stream stream = web.OpenRead(webServiceUrl);//创建和格式化 WSDL 文档。if (stream != null){// 格式化WSDLServiceDescription description = ServiceDescription.Read(stream);// 创建客户端代理类。ServiceDescriptionImporter importer = new ServiceDescriptionImporter{ProtocolName = "Soap",Style = ServiceDescriptionImportStyle.Client,CodeGenerationOptions =CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync};// 添加 WSDL 文档。importer.AddServiceDescription(description, null, null);//使用 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{GenerateExecutable = false,// 指定输出dll文件名。OutputAssembly = m_OutputDllFilename};parameter.ReferencedAssemblies.Add("System.dll");parameter.ReferencedAssemblies.Add("System.XML.dll");parameter.ReferencedAssemblies.Add("System.Web.Services.dll");parameter.ReferencedAssemblies.Add("System.Data.dll");// 编译输出程序集CompilerResults result = provider.CompileAssemblyFromDom(parameter, unit);// 使用 Reflection 调用 WebService。if (!result.Errors.HasErrors){BuildMethods();return true;}else{error = "反射生成dll文件时异常";}stream.Close();stream.Dispose();}elseerror = "打开WebServiceUrl失败";}catch (Exception ex){error = "异常:"+ex.Message;//Log.WriteLog(error);}return false;}/// <summary>/// 反射构建Methods/// </summary>private static void BuildMethods(){Assembly asm = Assembly.LoadFrom(m_OutputDllFilename);Type[] types = asm.GetTypes();Type asmType = asm.GetType(m_ProxyClassName);m_ObjInvoke = Activator.CreateInstance(asmType);var methods = Enum.GetNames(typeof(EMethod)).ToList();foreach (var item in methods){var methodInfo = asmType.GetMethod(item);if (methodInfo != null){var method = (EMethod)Enum.Parse(typeof(EMethod), item);m_MethodDic.Add(method, methodInfo);}}}/// <summary>/// 获取请求响应/// </summary>/// <param name="method"></param>/// <param name="para"></param>/// <returns></returns>public static string GetResponseString(EMethod method, params object[] para){string result = string.Empty;try{if (m_MethodDic.ContainsKey(method)){var temp = m_MethodDic[method].Invoke(m_ObjInvoke, para);if (temp != null)result = temp.ToString();}}catch { }return result;}}
}

调用方式:

            textBox1.AppendText("start get\r\n");string error = "";string param1 = "<?xml version=\"1.0\" encoding=\"GBK\" ?><request><patientid></patientid><accessionid>ZH230911DR8141</accessionid></request>";bool succ = WSHelper.CreateWebService(out error);textBox1.AppendText("error is:" + error + "\r\n");textBox1.AppendText("succ is:" + succ + "\r\n");string result = WSHelper.GetResponseString(EMethod.queryExamInfo, param1);textBox1.AppendText("result is:" + result + "\r\n");

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/79968.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

9月8日作业

思维导图 栈stack.h #ifndef STACK_H #define STACK_H #include <iostream> #define MAXSIZE 128using namespace std; class Stack { public://构造函数Stack();//析构函数~Stack();//拷贝构造函数Stack(const Stack &other);//入栈bool push(int value);//出栈并返…

技师学院物联网实训室建建设方案

一、概述 1.1专业背景 物联网&#xff08;Internet of Things&#xff09;被称为继计算机、互联网之后世界信息产业第三次浪潮&#xff0c;它并非一个全新的技术领域&#xff0c;而是现代信息技术发展到一定阶段后出现的一种聚合性应用与技术提升&#xff0c;是随着传感网、通…

Docker 恶意挖矿镜像应急实例

01、概述 当网络流量监控发现某台运行多个docker容器的主机主动连接到一个疑似挖矿矿池的地址时&#xff0c;需要快速响应和排查&#xff0c;以阻止进一步的损害。 面对docker容器的场景下&#xff0c;如何快速分析和识别恶意挖矿容器?本文将分享一种应急响应思路&#xff0c;…

ARTS打卡第三周

概述 infoq的arts打卡学习&#xff0c;贯彻左耳朵耗子的学习理念&#xff0c;活到老学到老&#xff0c;每天都精进一点&#xff0c;上个星期没有写打卡文档&#xff0c;只能用工作太忙为借口为自己开脱了 一、Algorithm 一道算法题 最近工作使用算法场景较少&#xff0c;基本上…

基于matlab实现的电力系统稳定性分析摆幅曲线代码

完整程序&#xff1a; clear; clc; t 0; tf 0; tfl 0.5; tc 0.5; % tc 0.05, 0.125, 0.5 sec for 2.5 cycles, 6.25 cycles & 25 cycles resp ts 0.05; m 2.52 / (180 * 50); i 2; dt 21.64 * pi / 180; ddt 0; time(1) 0; ang(1) 21.64; pm 0.9; pm1 2.44;…

Redis3.2.1如何设置远程连接?允许局域网访问

背景&#xff1a; 电脑A的redis需要开放给电脑B使用&#xff0c;二者处于同一局域网 【后面会补充更详细的踩坑历程&#xff0c;先发出来作为记录】 过程&#xff1a; 在你查了很多方法后&#xff0c;如果还是没有解决&#xff0c; 尝试考虑一下你的redis配置文件是不是修…

零基础VB6无壳P-CODE逆向分析(VB Decompiler应用与避坑)

> 前言 最近从朋友那里拿到了一个加密狗授权的软件安装包,秉承着LCG的精神,开启了逆向之路,经过查壳和综合分析确定是VB6编写的程序(这年头使用VB6开发商业程序的还真少见),作为一名C# Winform的业余程序员,靠着C#的知识勉强分析个大概. > 授权简介 软件共分三种授权模…

LeetCode LCP 50. 宝石补给

【LetMeFly】LCP 50.宝石补给 力扣题目链接&#xff1a;https://leetcode.cn/problems/WHnhjV/ 欢迎各位勇者来到力扣新手村&#xff0c;在开始试炼之前&#xff0c;请各位勇者先进行「宝石补给」。 每位勇者初始都拥有一些能量宝石&#xff0c; gem[i] 表示第 i 位勇者的宝…

一场深刻的开源聚会:KCC@北京 9.2 活动回顾

开源为我们带来了什么&#xff1f;这是这场聚会的宣传文的标题&#xff1a;https://mp.weixin.qq.com/s/5sR6TPEpQmYNBnCtVilkzg 同样这个问题也可以是极具个体化的&#xff1a;开源为我带来了什么&#xff1f;秋天的周末&#xff0c;预报有雨&#xff0c;北京的开源人还是相聚…

脚本:用python实现五子棋

文章目录 1. 语言2. 效果3. 脚本4. 解读5. FutureReference 1. 语言 Python 无环境配置、无库安装。 2. 效果 以第一回合为例 玩家X 玩家0 3. 脚本 class GomokuGame:def __init__(self, board_size15):self.board_size board_sizeself.board [[ for _ in range(board_…

RecursionError: maximum recursion depth exceeded while calling a Python object

The “RecursionError: maximum recursion depth exceeded” error occurs when a function calls itself recursively too many times, exceeding the maximum recursion depth set by Python. This error is usually triggered by an infinite recursion loop. To fix this …

对IP协议概念以及IP地址的概念进行简单整理

网络层重要协议 参考模型和协议栈IP协议IPv4数据报IP数据报格式IPv4地址特殊IP地址私有IP地址和公有IP地址子网划分 参考模型和协议栈 IP协议 IP协议定义了网络层数据传送的基本单元&#xff0c;也制定了一系列关于网络层的规则。 IPv4数据报 网络层的协议数据单元PDU 叫做分…

使用Java实现蚁群优化算法解决流水车间调度问题:全面指南与详细代码解析

1. 引言 在现代的制造业中,流水车间调度问题是一个经常被研究的复杂组合优化问题。简单地说,这是一个关于如何安排机器上的任务,以便在满足各种约束条件的前提下,最大化或最小化某些特定的性能指标。例如,最小化完成所有任务的总时间或最大化产出。 为了解决这一问题,许…

基于Java+SpringBoot+Vue+uniapp点餐小程序(包含协同过滤算法和会员系统,强烈推荐!)

校园点餐小程序 一、前言二、我的优势2.1 自己的网站2.2 自己的小程序&#xff08;小蔡coding&#xff09;2.3 有保障的售后2.4 福利 三、开发环境与技术3.1 MySQL数据库3.2 Vue前端技术3.3 Spring Boot框架3.4 微信小程序 四、功能设计4.1 系统功能结构设计4.2 主要功能描述 五…

【初阶数据结构】栈和队列——C语言(详解)

目录 一、栈 1.1栈的概念及结构 1.2栈的实现 1.2.1静态栈的实现 1.3动态栈的实现 1.3.1栈的创建 1.3.2栈的初始化 1.3.3栈的清空销毁 1.3.4栈的元素插入 1.3.5栈顶元素的删除 1.3.6返回栈顶数据 1.3.7求栈的大小 1.3.8判断栈是否为空 二、栈的实现完整代码 三、队…

rust结构体

一、定义结构体类型 语法 struct Name_of_structure {field1: data_type,field2: data_type,field3: data_type, }注意&#xff1a; 不同于C&#xff0c;Rust的struct语句仅用来定义类型&#xff0c;不能定义实例。 结尾不需要;。 每个字段定义之后用 , 分隔。最后一个逗号可…

Unity 动画系统

动画系统包含&#xff1a; 动画片段 Animation Clip&#xff0c;记录物体变化的信息&#xff0c;可以是角色的闪转腾挪&#xff0c;也可以是一扇门的开闭动画状态机 Animator Controller&#xff0c;根据设置切换动画片段动画组件 Animator&#xff0c;Animation替身 Avatar&a…

数据结构基础8:二叉树oj+层序遍历。

二叉树oj层序遍历 题目一&#xff1a;二叉树的销毁&#xff1a;方法一&#xff1a;前序遍历&#xff1a;方法二&#xff1a;后序遍历&#xff1a; 题目二&#xff1a;二叉树查找值为x的节点方法一&#xff1a;方法二&#xff1a;方法三&#xff1a; 题目三&#xff1a;层序遍历…

Python 和 MatLab 模拟粒子动力系统

力计算 我们将假设一个由 N N N 个点粒子组成的系统&#xff0c;索引为 i 1 , … , N i1, \ldots, N i1,…,N。每个粒子都有一个&#xff1a; 质量 m i m_i mi​ 位置 r i [ x i , y i , z i ] r_{\boldsymbol{i}}\left[x_i, y_i, z_i\right] ri​[xi​,yi​,zi​] 速…

透视俄乌网络战之二:Conti勒索软件集团(下)

透视俄乌网络战之一&#xff1a;数据擦除软件 透视俄乌网络战之二&#xff1a;Conti勒索软件集团&#xff08;上&#xff09; Conti勒索软件集团&#xff08;下&#xff09; 1. 管理面板源代码2. Pony凭证窃取恶意软件3. TTPs4. Conti Locker v2源代码5. Conti团伙培训材料6. T…