C# 调用WebService的方式汇总

2023-05-16

C# 调用WebService的方式汇总

    • 方式一:根据提供的webservice地址,用VS自带工具生成cs文件,添加到项目中使用即可。
    • 方式二:根据webservice地址,动态在项目中生成代理类文件,通过反射调用即可
    • 方式三:通过 HttpWebRequest 直接调用webservice中的函数

方式一:根据提供的webservice地址,用VS自带工具生成cs文件,添加到项目中使用即可。

工具:
在这里插入图片描述
在这里插入图片描述

步骤一:如果本地访问不了webservice地址,则通过远端生成wsdl文件,拷贝到本地用工具生成cs类文件,导入项目中。

1.获取webservice地址;

2.在浏览器中访问webservice地址,此处访问需要在地址后面加上 ?wsdl

例如:原地址:http://42.123.92.137:1010/interface/Hospital_Interface.asmx

访问时:http://42.123.92.137:1010/interface/Hospital_Interface.asmx?wsdl

3.将网页中的数据另存为 (xxx.wsdl)文件,

3.用VS自带工具将上一步生成的(xxx.wsdl)文件通过命令生成 (xxx.cs) 类文件。

(1)直接通过wsdl文件位置生成。公式:wsdl + wsdl文件路径 + /out:+ cs生成文件路径

例:wsdl E:\service.wsdl /out:E:/WebServicetest.cs

(2)生成带有命名空间的cs文件。公式:wsdl + wsdl文件路径 + /n:命名空间名称 +/out:+ cs生成文件路径

例:wsdl E:\service.wsdl /n:test /out:E:/WebServicetest.cs

步骤二:如果本地可以直接访问到webservice地址,直接通过VS工具生成

生成公式:wsdl /n:+命名空间名称+ /out:+cs类文件路径+文件名称.cs+ webservice地址+?wsdl (注意公式里面空格的地方)

例:wsdl /n:xx /out:D:/web.cs http://192.168.0.222/WebSite/Service.asmx?wsdl

方式二:根据webservice地址,动态在项目中生成代理类文件,通过反射调用即可

1.将webservice地址存放到配置文件中,代码中通过读取地址生成代理类。

/// <summary>
        /// 根据webservice地址生成代理类
        /// </summary>
        /// <param name="url">本地配置文件中webservice地址</param>
        /// <returns></returns>
        public static int InitCreatClass(string url)
        {
            try
            {

                //使用 XmlTextReader 对象创建和格式化 WSDL 文档
                XmlTextReader reader = new XmlTextReader(url + "?wsdl");
                ServiceDescription serviceDes = ServiceDescription.Read(reader);


                ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
                sdi.AddServiceDescription(serviceDes, "", "");
                CodeNamespace cnspace = new CodeNamespace(@namespace);

                //生成客户端代理类
                CodeCompileUnit ccUnit = new CodeCompileUnit();
                ccUnit.Namespaces.Add(cnspace);
                sdi.Import(cnspace, ccUnit);
                CSharpCodeProvider cscProvider = new CSharpCodeProvider();
                ICodeCompiler icc = cscProvider.CreateCompiler();

                //设置编译参数
                CompilerParameters copParameters = new CompilerParameters();
                copParameters.GenerateExecutable = false;
                copParameters.GenerateInMemory = true;
                copParameters.OutputAssembly = "TestWebService.dll";
                copParameters.ReferencedAssemblies.Add("System.dll");
                copParameters.ReferencedAssemblies.Add("System.XML.dll");
                copParameters.ReferencedAssemblies.Add("System.Web.Services.dll");
                copParameters.ReferencedAssemblies.Add("System.Data.dll");

                //编译代理类
                CompilerResults comResults = icc.CompileAssemblyFromDom(copParameters, ccUnit);
                if (true == comResults.Errors.HasErrors)
                {

                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    foreach (System.CodeDom.Compiler.CompilerError ce in comResults.Errors)
                    {
                        sb.Append(ce.ToString());
                        sb.Append(System.Environment.NewLine);
                    }
                    throw new Exception(sb.ToString());
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return 0;
        }

2.访问代理类,调用类中的函数

/// <summary>
     /// 调用代理类函数
     /// </summary>
     /// <param name="methodname">函数名称</param>
     /// <param name="args">入参</param>
     /// <returns></returns>
     public static object InvokeWebService(string methodname, object[] args)
        {
            try
            {
                //通过反射调用代理类函数
                System.Reflection.Assembly asm = System.Reflection.Assembly.LoadFrom("TestWebService.dll");
                Type t = asm.GetType(classname);

                object o = Activator.CreateInstance(t);
                System.Reflection.MethodInfo method = t.GetMethod(methodname);
                return method.Invoke(o, args);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.InnerException.Message, new Exception(ex.InnerException.StackTrace));
            }
        }

     /// <summary>
        /// 函数调用
        /// </summary>
        private void TestInvoke()
        {
            string[] ReqParms = new string[4];//参数数量
            ReqParms[0] = "参数1";
            ReqParms[1] = "参数2";
            ReqParms[2] = "参数3";
            ReqParms[3] = "参数4";

            //Func_Name  被调用函数名称
            string result = InvokeWebServiceD("Func_Name", ReqParms).ToString();
        }

方式三:通过 HttpWebRequest 直接调用webservice中的函数

构建httprequest帮助类

public partial class HttpHelper
    {
        private static HttpHelper m_Helper;

        /// <summary>
        /// 单例模式
        /// </summary>
        public static HttpHelper Helper
        {
            get { return m_Helper ?? (m_Helper = new HttpHelper()); }
        }

        /// <summary>
        /// 获取请求的数据
        /// </summary>
        /// <param name="strUrl">请求地址</param>
        /// <param name="requestMode">请求方式</param>
        /// <param name="parameters">参数</param>
        /// <param name="requestCoding">请求编码</param>
        /// <param name="responseCoding">响应编码</param>
        /// <param name="timeout">请求超时时间(毫秒)</param>
        /// <returns>请求成功响应信息,失败返回null</returns>
        public string GetResponseString(string strUrl, ERequestMode requestMode, Dictionary<string, string> parameters, Encoding requestCoding, Encoding responseCoding, int timeout = 300)
        {
            string url = VerifyUrl(strUrl);
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url));

            HttpWebResponse webResponse = null;
            switch (requestMode)
            {
                case ERequestMode.Get:
                    webResponse = GetRequest(webRequest, timeout);
                    break;
                case ERequestMode.Post:
                    webResponse = PostRequest(webRequest, parameters, timeout, requestCoding);
                    break;
            }

            if (webResponse != null && webResponse.StatusCode == HttpStatusCode.OK)
            {
                using (Stream newStream = webResponse.GetResponseStream())
                {
                    if (newStream != null)
                        using (StreamReader reader = new StreamReader(newStream, responseCoding))
                        {
                            string result = reader.ReadToEnd();
                            return result;
                        }
                }
            }
            return null;
        }


        /// <summary>
        /// get 请求指定地址返回响应数据
        /// </summary>
        /// <param name="webRequest">请求</param>
        /// <param name="timeout">请求超时时间(毫秒)</param>
        /// <returns>返回:响应信息</returns>
        private HttpWebResponse GetRequest(HttpWebRequest webRequest, int timeout)
        {
            try
            {
                webRequest.Accept = "text/html, application/xhtml+xml, application/json, text/javascript, */*; q=0.01";
                webRequest.Headers.Add("Accept-Language", "zh-cn,en-US,en;q=0.5");
                webRequest.Headers.Add("Cache-Control", "no-cache");
                webRequest.UserAgent = "DefaultUserAgent";
                webRequest.Timeout = timeout;
                webRequest.Method = "GET";

                // 接收返回信息
                HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
                return webResponse;
            }
            catch (Exception ex)
            {
                return null;
            }
        }


        /// <summary>
        /// post 请求指定地址返回响应数据
        /// </summary>
        /// <param name="webRequest">请求</param>
        /// <param name="parameters">传入参数</param>
        /// <param name="timeout">请求超时时间(毫秒)</param>
        /// <param name="requestCoding">请求编码</param>
        /// <returns>返回:响应信息</returns>
        private HttpWebResponse PostRequest(HttpWebRequest webRequest, Dictionary<string, string> parameters, int timeout, Encoding requestCoding)
        {
            try
            {
                // 拼接参数
                string postStr = string.Empty;
                if (parameters != null)
                {
                    parameters.All(o =>
                    {
                        if (string.IsNullOrEmpty(postStr))
                            postStr = string.Format("{0}={1}", HttpUtility.UrlEncode(o.Key), HttpUtility.UrlEncode(o.Value));
                        else
                            postStr += string.Format("&{0}={1}", HttpUtility.UrlEncode(o.Key), HttpUtility.UrlEncode(o.Value));

                        return true;
                    });
                }

                byte[] byteArray = requestCoding.GetBytes(postStr);
                webRequest.Accept = "text/html, application/xhtml+xml, application/json, text/javascript, */*; q=0.01";
                webRequest.Headers.Add("Accept-Language", "zh-cn,en-US,en;q=0.5");
                webRequest.Headers.Add("Cache-Control", "no-cache");
                webRequest.UserAgent = "DefaultUserAgent";
                //webRequest.Timeout = timeout;
                webRequest.ContentType = "application/x-www-form-urlencoded";
                webRequest.ContentLength = byteArray.Length;
                webRequest.Method = "POST";

                // 将参数写入流
                using (Stream newStream = webRequest.GetRequestStream())
                {
                    newStream.Write(byteArray, 0, byteArray.Length);
                    newStream.Close();
                }

                // 接收返回信息
                HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
                return webResponse;
            }
            catch (Exception ex)
            {
                return null;
            }
        }


        /// <summary>
        /// 验证URL
        /// </summary>
        /// <param name="url">待验证 URL</param>
        /// <returns></returns>
        private string VerifyUrl(string url)
        {
            if (string.IsNullOrEmpty(url))
                throw new Exception("URL 地址不可以为空!");

            if (url.StartsWith("http://", StringComparison.CurrentCultureIgnoreCase))
                return url;

            return string.Format("http://{0}", url);
        }

    }

    public enum ERequestMode
    {
        Get,
        Post
    }

调用方式

/// <summary>
        /// 测试调用
        /// </summary>
        private void TestInvoke()
        {
            //组织参数
            Dictionary<string, string> parameters = new Dictionary<string, string>();
            parameters.Add("CantonCode", PersonInfo.RegionNumber);
            parameters.Add("CardCode", PersonInfo.CardNo);
            parameters.Add("Name", txtName.Text);
            parameters.Add("CompHosCode", SystemConfigData.HospitalCode);

            string _result = HttpHelper.Helper.GetResponseString(url, ERequestMode.Post, parameters, Encoding.Default, Encoding.UTF8);
        }

以下是对上面三种方式进行总结。

方式一、

优点:利用地址直接生成cs类,操作方便快捷,发生错误机率小,调用简单;

缺点:如果webservice地址或者内容发生改变,项目必须重新生成cs文件,导致项目维护性差;

采用场景:webservice接口已经趋于稳定,不会有变动的情况下可使用这种方式;

方式二、

优点:将webservice地址放在配置文件中,一旦地址放生变化,只需要修改配置文件即可,项目维护性好;

缺点:对webservice接口要求比较高,不规范的webservice接口,生成代理类时会发生错误;

采用场景:webservice接口规范,且变动小时,可采用此种方式;

方式三、

优点:添加帮助类,然后调用即可,方便快捷,webservice地址放置在配置文件中,易于维护;

缺点:暂时未发现较大缺点;

采用场景:任何webservice接口,均可采用此种方式;

使用推荐:方式三 > 方式一 > 方式二

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C# 调用WebService的方式汇总 的相关文章

随机推荐

  • QT等待动态图gif加载透明背景lable

    h QLabel span class token operator span waiting span class token punctuation span QMovie span class token operator span
  • Week12 作业 B - 必做题(三维空间迷宫)

    一 题目描述 zjm被困在一个三维的空间中 现在要寻找最短路径逃生 xff01 空间由立方体单位构成 zjm每次向上下前后左右移动一个单位需要一分钟 xff0c 且zjm不能对角线移动 空间的四周封闭 zjm的目标是走到空间的出口 是否存在
  • Week13 作业 A - TT 的神秘任务1(必做)

    一 题目描述 这一天 xff0c TT 遇到了一个神秘人 神秘人给了两个数字 xff0c 分别表示 n 和 k xff0c 并要求 TT 给出 k 个奇偶性相同的正整数 xff0c 使得其和等于 n 例如 n 61 10 xff0c k 6
  • CentOS 7:使用技巧

    写在前面 主要是记录一下CentOS 7的一些使用技巧 一 添加拼音输入法 默认的输入法只有英文的输入 xff0c 需要自行添加中文的输入法 点击左上角的Applications xff0c 选择System Tools中的Settings
  • ubuntu安装php7.3

    php7 3的安装 按顺序输入命令 sudo apt get install software properties common python software propertiessudo add apt repository ppa
  • 多数据库数据列表分页

    多数据库查询数据列表分页 概述 xff1a 在后台管理系统中 列表数据的展示有可能来自多个数据源 xff0c 列表页需要支持分页 这边有两种方案 多个数据源的数据定时同步到某一个数据源A中 xff0c 列表显示的数据就从数据源A中进行分页查
  • ubuntu安装postman

    ubuntu安装postman postman官网下载压缩包点击此处 下载完成之后 把压缩包到桌面路径上 解压文件之后 通过命令 xff1a span class token punctuation span span class toke
  • mac docker + nginx + php

    链接地址 https www phpbloger com article 505 html
  • docker nginx 多个php版本

    链接 https cloud tencent com developer article 1554052
  • docke+nginx+php

    docker run name nginx p 8001 8001 p 8002 8002 v docker nginx www www v docker nginx conf nginx conf etc nginx conf d v d
  • 一个基于layui的简单组件,基于jquery的简单组件,layMin有简洁的提示框和图片预览、及加载效果等

    layMin扩展组件 一个基于layui的简单组件 xff0c 基于jquery的简单组件 xff0c layMin有简洁的提示框和图片预览 及加载效果等 xff1b 支持作为layui的组件引入 xff0c 也支持单独引入layMin c
  • Linux嵌入式终端的脚本,检测有没插网线

    span class token shebang important bin sh span span class token assign left variable NETWORK span span class token opera
  • Ubuntu20.04系统下进行复制粘贴文件显示没有权限的解决办法

    Ctrl 43 alt 43 T打开终端输入命令sudo nautilus然后就可以打开一个不需要管理员权限的界面 xff0c 可以直接复制粘贴 亲测有效 xff01 xff01 借鉴于博客 xff1a https blog csdn ne
  • Ubuntu20.04安装anaconda3成功以后,找不到conda命令

    原因 xff1a 环境设置没有更新 解决办法 xff1a 注意路径 xff01 找到anaconda安装完成后生成的文件夹位置 相应修改 xff0c 如下图我的位置就在主目录下 xff1a 因此 xff0c 我执行的命令为 xff1a ec
  • ubuntu16.04 opencv打开摄像头失败

    ubuntu16 04 opencv打开摄像头失败 按照opencv检测AruCo标记教程 xff0c 运行程序时打开摄像头失败 xff0c 使用的相机是Intel RealSense D435 发生问题的代码如下 span class t
  • 计算机视觉学习笔记&思维导图(一起轻松学习计算机视觉与图像处理)

    文章目录 前言一 思维导图二 笔记勘误 前言 本文为计算机视觉课程期末复习的笔记 xff0c 编者耗时近半个月整理而成 内容依据课程的学习资料以及查阅网上一些资料梳理得到的 xff0c 编者希望在应付考试的同时能够将计算机视觉的知识体系建立
  • python发送邮件

    text 61 39 亲爱的Jerry 我是你的邻居Tom xff01 5 1邀请你来参加劳动 xff01 CALL ME xff1a 123 64 qq com 39 from email mime text import MIMETex
  • Python实现微信自动化发送信息

    需求 xff1a 利用PC端微信实现自动向文件传输助手 xff0c 好友等发送信息 库说明 psutil 获取系统运行的进程和系统利用率 xff08 包括CPU 内存 磁盘 网络等 xff09 信息 xff0c 用于获取进程ID pywin
  • 数据类型——枚举

    文章目录 枚举是什么枚举的声明枚举与其他数据类型的转换与int类型转换枚举转intint转枚举 与string类型转换枚举转字符串字符串转枚举 枚举的意义是什么 枚举是什么 在c 中 xff0c 枚举 enumeration 是一种数据类型
  • C# 调用WebService的方式汇总

    C 调用WebService的方式汇总 方式一 xff1a 根据提供的webservice地址 xff0c 用VS自带工具生成cs文件 xff0c 添加到项目中使用即可 方式二 xff1a 根据webservice地址 xff0c 动态在项