1、建立项目WebService和WinForm项目,这里起名为WinFormInvokeWebService,如图所示,

2、Service1.asmx代码为:(这部分其实和上篇的代码是一样的)

  1. using System;
  2.  
  3. using System.Collections.Generic;
  4.  
  5. using System.Linq;
  6.  
  7. using System.Web;
  8.  
  9. using System.Web.Services;
  10.  
  11. using System.Data;
  12.  
  13. namespace WebService1
  14.  
  15. {
  16.  
  17. /// <summary>
  18.  
  19. /// Service1 的摘要说明
  20.  
  21. /// </summary>
  22.  
  23. [WebService(Namespace = "http://tempuri.org/")]
  24.  
  25. [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
  26.  
  27. [System.ComponentModel.ToolboxItem(false)]
  28.  
  29. // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
  30.  
  31. [System.Web.Script.Services.ScriptService]
  32.  
  33. public class Service1 : System.Web.Services.WebService
  34.  
  35. {
  36.  
  37. //无参方法
  38.  
  39. [WebMethod]
  40.  
  41. public string HelloWorld()
  42.  
  43. {
  44.  
  45. return "Hello World";
  46.  
  47. }
  48.  
  49. //有参方法1
  50.  
  51. [WebMethod]
  52.  
  53. public int Add(int a, int b)
  54.  
  55. {
  56.  
  57. return a + b;
  58.  
  59. }
  60.  
  61. //有参方法2
  62.  
  63. [WebMethod]
  64.  
  65. public int Sum(int x)
  66.  
  67. {
  68.  
  69. int sum = ;
  70.  
  71. for (int i = ; i <= x; i++)
  72.  
  73. {
  74.  
  75. sum += i;
  76.  
  77. }
  78.  
  79. return sum;
  80.  
  81. }
  82.  
  83. // 返回一个复合类型
  84.  
  85. [WebMethod]
  86.  
  87. public Student GetStudentByStuNo(string stuNo)
  88.  
  89. {
  90.  
  91. if(stuNo=="")
  92.  
  93. return new Student { StuNo = "", StuName = "张三" };
  94.  
  95. if(stuNo=="")
  96.  
  97. return new Student { StuNo = "", StuName = "李四" };
  98.  
  99. return null;
  100.  
  101. }
  102.  
  103. //返回返回泛型集合的
  104.  
  105. [WebMethod]
  106.  
  107. public List<Student> GetList()
  108.  
  109. {
  110.  
  111. List<Student> list = new List<Student>();
  112.  
  113. list.Add(new Student() { StuNo = "", StuName = "张三" });
  114.  
  115. list.Add(new Student() { StuNo = "", StuName = "李四" });
  116.  
  117. list.Add(new Student() { StuNo = "", StuName = "王五" });
  118.  
  119. return list;
  120. }
  121.  
  122. //返回DataSet
  123.  
  124. [WebMethod]
  125.  
  126. public DataSet GetDataSet()
  127.  
  128. {
  129.  
  130. DataSet ds = new DataSet();
  131.  
  132. DataTable dt = new DataTable();
  133.  
  134. dt.Columns.Add("StuNo", Type.GetType("System.String"));
  135.  
  136. dt.Columns.Add("StuName", Type.GetType("System.String"));
  137.  
  138. DataRow dr = dt.NewRow();
  139.  
  140. dr["StuNo"] = ""; dr["StuName"] = "张三";
  141.  
  142. dt.Rows.Add(dr);
  143.  
  144. dr = dt.NewRow();
  145.  
  146. dr["StuNo"] = ""; dr["StuName"] = "李四";
  147.  
  148. dt.Rows.Add(dr);
  149.  
  150. ds.Tables.Add(dt);
  151.  
  152. return ds;
  153.  
  154. }
  155.  
  156. }
  157.  
  158. public class Student
  159.  
  160. {
  161.  
  162. public string StuNo { get; set; }
  163.  
  164. public string StuName { get; set; }
  165.  
  166. }
  167.  
  168. }

3、在WebService的web.config文件的system.web节下面加上以下配置。如果不添加在运行手工发送HTTP请求调用WebService(利用GET方式)时,总是出现“远程服务器返回错误: (500) 内部服务器错误。”就是这个该死的错误,让我浪费2个多小时

  1. <webServices>
  2.  
  3. <protocols>
  4.  
  5. <add name="HttpPost" />
  6.  
  7. <add name="HttpGet" />
  8.  
  9. </protocols>
  10.  
  11. </webServices>

4、在WinForm应用程序里添加Web引用,有人会发现选择WinForm项目里只能添加服务引用,我当初也是这么认为后来,后来发现在做异步的调用的时候有些方法实在点不出来,所以这里说下如何添加Web引用,选择项目WinFormInvokeWebService右键->添加服务引用,弹出以下对话框

(1)选择高级

(2)选择添加web引用

(3)选择“此解决方案中的Web服务”

(4)选择Service1

(5)在web引用名里输入一个服务名称,这里使用默认的名称localhost,点添加引用

5、添加3个Windows窗体,

(1)Form1拖放的控件为:

Form1的代码为:

  1. using System;
  2.  
  3. using System.Collections.Generic;
  4.  
  5. using System.ComponentModel;
  6.  
  7. using System.Data;
  8.  
  9. using System.Drawing;
  10.  
  11. using System.Linq;
  12.  
  13. using System.Text;
  14.  
  15. using System.Windows.Forms;
  16.  
  17. namespace WinFormInvokeWebService
  18.  
  19. {
  20.  
  21. public partial class Form1 : Form
  22.  
  23. {
  24.  
  25. public Form1()
  26.  
  27. {
  28.  
  29. InitializeComponent();
  30.  
  31. }
  32.  
  33. private void button1_Click(object sender, EventArgs e)
  34.  
  35. {
  36.  
  37. localhost.Service1 service = new localhost.Service1();
  38.  
  39. localhost.Student s = service.GetStudentByStuNo("");
  40.  
  41. MessageBox.Show("学号:" + s.StuNo + ",姓名:" + s.StuName);
  42.  
  43. }
  44.  
  45. private void button2_Click(object sender, EventArgs e)
  46.  
  47. {
  48.  
  49. new Form2().Show();
  50.  
  51. }
  52.  
  53. private void button3_Click(object sender, EventArgs e)
  54.  
  55. {
  56.  
  57. new Form3().Show();
  58.  
  59. }
  60.  
  61. }
  62. }

(2)Form2拖放的控件为:

Form2的代码为:

  1. using System;
  2.  
  3. using System.Collections.Generic;
  4.  
  5. using System.ComponentModel;
  6.  
  7. using System.Data;
  8.  
  9. using System.Drawing;
  10.  
  11. using System.Linq;
  12.  
  13. using System.Text;
  14.  
  15. using System.Windows.Forms;
  16.  
  17. //导入此命名空间
  18.  
  19. using System.Net;
  20.  
  21. using System.Xml;
  22.  
  23. using System.IO;
  24.  
  25. using System.Web; //先添加System.Web引用再导入此命名空间
  26.  
  27. namespace WinFormInvokeWebService
  28.  
  29. {
  30.  
  31. public partial class Form2 : Form
  32.  
  33. {
  34.  
  35. public Form2()
  36.  
  37. {
  38.  
  39. InitializeComponent();
  40.  
  41. }
  42.  
  43. //手工发送HTTP请求调用WebService-GET方式
  44.  
  45. private void button1_Click(object sender, EventArgs e)
  46.  
  47. {
  48.  
  49. //http://localhost:3152注意你的地址可能和我的不一样,运行WebService看下你的端口改下
  50.  
  51. string strURL = "http://localhost:3152/Service1.asmx/GetStudentByStuNo?stuNo=";
  52.  
  53. strURL += this.textBox1.Text;
  54.  
  55. //创建一个HTTP请求
  56.  
  57. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
  58.  
  59. //request.Method="get";
  60.  
  61. HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
  62.  
  63. Stream s = response.GetResponseStream();
  64.  
  65. XmlTextReader Reader = new XmlTextReader(s);
  66.  
  67. Reader.MoveToContent();
  68.  
  69. string strValue = Reader.ReadInnerXml();
  70.  
  71. strValue = strValue.Replace("&lt;", "<");
  72.  
  73. strValue = strValue.Replace("&gt;", ">");
  74.  
  75. MessageBox.Show(strValue);
  76.  
  77. Reader.Close();
  78.  
  79. }
  80.  
  81. //手工发送HTTP请求调用WebService-POST方式
  82.  
  83. private void button2_Click(object sender, EventArgs e)
  84.  
  85. {
  86.  
  87. //http://localhost:3152注意你的地址可能和我的不一样,运行WebService看下你的端口改下
  88.  
  89. string strURL = "http://localhost:3152/Service1.asmx/GetStudentByStuNo";
  90.  
  91. //创建一个HTTP请求
  92.  
  93. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
  94.  
  95. //Post请求方式
  96.  
  97. request.Method = "POST";
  98.  
  99. //内容类型
  100.  
  101. request.ContentType = "application/x-www-form-urlencoded";
  102.  
  103. //参数经过URL编码
  104.  
  105. string paraUrlCoded = HttpUtility.UrlEncode("stuNo");
  106.  
  107. paraUrlCoded += "=" + HttpUtility.UrlEncode(this.textBox1.Text);
  108.  
  109. byte[] payload;
  110.  
  111. //将URL编码后的字符串转化为字节
  112.  
  113. payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
  114.  
  115. //设置请求的ContentLength
  116.  
  117. request.ContentLength = payload.Length;
  118.  
  119. //获得请求流
  120.  
  121. Stream writer = request.GetRequestStream();
  122.  
  123. //将请求参数写入流
  124.  
  125. writer.Write(payload, , payload.Length);
  126.  
  127. //关闭请求流
  128.  
  129. writer.Close();
  130.  
  131. //获得响应流
  132.  
  133. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  134.  
  135. Stream s = response.GetResponseStream();
  136.  
  137. XmlTextReader Reader = new XmlTextReader(s);
  138.  
  139. Reader.MoveToContent();
  140.  
  141. string strValue = Reader.ReadInnerXml();
  142.  
  143. strValue = strValue.Replace("&lt;", "<");
  144.  
  145. strValue = strValue.Replace("&gt;", ">");
  146.  
  147. MessageBox.Show(strValue);
  148.  
  149. Reader.Close();
  150.  
  151. }
  152.  
  153. }
  154.  
  155. }

(3)Form3拖放的控件为:

Form3的代码为:

  1. using System;
  2.  
  3. using System.Collections.Generic;
  4.  
  5. using System.ComponentModel;
  6.  
  7. using System.Data;
  8.  
  9. using System.Drawing;
  10.  
  11. using System.Linq;
  12.  
  13. using System.Text;
  14.  
  15. using System.Windows.Forms;
  16.  
  17. namespace WinFormInvokeWebService
  18.  
  19. {
  20.  
  21. public partial class Form3 : Form
  22.  
  23. {
  24.  
  25. public Form3()
  26.  
  27. {
  28.  
  29. InitializeComponent();
  30.  
  31. }
  32.  
  33. //利用Backgroundworker对象
  34.  
  35. private void button1_Click(object sender, EventArgs e)
  36.  
  37. {
  38.  
  39. BackgroundWorker backgroundworker = new BackgroundWorker();
  40.  
  41. // 注册具体异步处理的方法
  42.  
  43. backgroundworker.DoWork += new DoWorkEventHandler(back_DoWork);
  44.  
  45. // 注册调用完成后的回调方法
  46.  
  47. backgroundworker.RunWorkerCompleted += newRunWorkerCompletedEventHandler(back_RunWorkerCompleted);
  48.  
  49. // 这里开始异步调用
  50.  
  51. backgroundworker.RunWorkerAsync();
  52.  
  53. //调用服务的同时客户端处理并不停止
  54.  
  55. ChangeProcessBar();
  56.  
  57. }
  58.  
  59. //完成事件
  60.  
  61. void back_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
  62.  
  63. {
  64.  
  65. if (e.Error != null)
  66.  
  67. throw e.Error;
  68.  
  69. progressBar1.Value = progressBar1.Maximum; //调用完成了,把客户端进度条填充满
  70.  
  71. localhost.Student s = e.Result as localhost.Student; //获取处理结果
  72.  
  73. MessageBox.Show("学号:" + s.StuNo + ",姓名:" + s.StuName); //显示从服务器获取的结果值
  74.  
  75. }
  76.  
  77. //调用方法
  78.  
  79. void back_DoWork(object sender, DoWorkEventArgs e)
  80.  
  81. {
  82.  
  83. // Web Service代理类
  84.  
  85. localhost.Service1 service = new localhost.Service1();
  86.  
  87. // 调用Web方法GetClass1,结果赋值给DoWorkEventArgs的Result对象
  88.  
  89. e.Result = service.GetStudentByStuNo("");
  90.  
  91. }
  92.  
  93. /// <summary>
  94.  
  95. /// 界面的进度条显示
  96.  
  97. /// </summary>
  98.  
  99. void ChangeProcessBar()
  100.  
  101. {
  102.  
  103. for (int i = ; i < ; i++)
  104.  
  105. {
  106.  
  107. progressBar1.Value = i;
  108.  
  109. System.Threading.Thread.Sleep();
  110.  
  111. }
  112.  
  113. }
  114.  
  115. //调用WebMethod的Async方法
  116.  
  117. private void button2_Click(object sender, EventArgs e)
  118.  
  119. {
  120.  
  121. // Web Service代理类
  122.  
  123. localhost.Service1 service = new localhost.Service1();
  124.  
  125. //这里开始异步调用
  126.  
  127. //service.GetProductPriceAsync("001");
  128.  
  129. service.GetStudentByStuNoAsync("");
  130.  
  131. // 注册调用完成后的回调方法
  132.  
  133. service.GetStudentByStuNoCompleted += newlocalhost.GetStudentByStuNoCompletedEventHandler(GetStudentByStuNoCompleted);
  134.  
  135. //调用同时客户端处理不停止
  136.  
  137. ChangeProcessBar();
  138.  
  139. }
  140.  
  141. //完成事件
  142.  
  143. void GetStudentByStuNoCompleted(object sender, localhost.GetStudentByStuNoCompletedEventArgs e)
  144.  
  145. {
  146.  
  147. if (e.Error != null)
  148.  
  149. throw e.Error;
  150.  
  151. progressBar1.Value = progressBar1.Maximum; //调用完成了,把客户端进度条填充满
  152.  
  153. localhost.Student s = e.Result as localhost.Student; //获取处理结果
  154.  
  155. MessageBox.Show("学号:" + s.StuNo + ",姓名:" + s.StuName); //显示从服务器获取的结果值
  156.  
  157. }
  158. }
  159. }

运行结果:

[转]WinForm如何调用Web Service的更多相关文章

  1. C#之VS2010ASP.NET页面调用Web Service和winform程序调用Web Service

    一:用ASP.NET调用Web Service 打开VS2010,打开“文件-新建-网站”,选择“ASP.NET网站” 选好存储位置,语言后点击确定,进入默认页面.然后先添加Web引用,把WebSer ...

  2. WinForm如何调用Web Service

    参考地址 今天看了李天平关于WinForm调用Web Service的代码,我自己模仿做一个代码基本都是复制粘贴的,结果不好使.郁闷的是,又碰到那个该死的GET调用Web Service,我想肯定又是 ...

  3. ORACLE存储过程调用Web Service

    1. 概述 最近在ESB项目中,客户在各个系统之间的服务调用大多都是在oracle存储过程中进行的,本文就oracle存储过程调用web service来进行说明.其他主流数据库,比如mysql和sq ...

  4. C#开发和调用Web Service

    http://blog.csdn.net/h0322/article/details/4776819 1.1.Web Service基本概念 Web Service也叫XML Web Service ...

  5. php5调用web service

    工作中需要用php调用web service接口,对php不熟,上网搜搜,发现关于用php调用web service的文章也不多,不少还是php4里用nusoap这个模块调用的方法,其实php5里已经 ...

  6. 通过ksoap2-android来调用Web Service操作的实例

    import java.io.IOException; import org.ksoap2.SoapEnvelope;import org.ksoap2.serialization.SoapObjec ...

  7. 使用Android应用调用Web Service

    Java本身提供了丰富的Web  Service支持,比如Sun公司指定的JAX-WS  2规范,还有Apache开源组织所提供的Axis1.Axis2.CXF等,这些技术不仅可以用于非常方便地对外提 ...

  8. Dynamic CRM 2013学习笔记(二十五)JS调用web service 实现多条记录复制(克隆)功能

    前面介绍过如何克隆一条当前的记录: Dynamic CRM 2013学习笔记(十四)复制/克隆记录 , 主要是通过界面上加一个字段,单击form上的clone 按钮时,改变这个字段的值以触发插件来实现 ...

  9. ASP.NET调用Web Service

    1.1.Web Service基本概念 Web Service也叫XML Web Service WebService是一种可以接收从Internet或者Intranet上的其它系统中传递过来的请求, ...

随机推荐

  1. RX学习笔记:Bootstrap

    Bootstrap https://getbootstrap.com 2016-07-01 在学习FreeCodeCamp课程中了解到Bootstrap,并于课程第一个实战题卡在响应式部分,于是先对B ...

  2. JS判断上传图片格式是否正确

    <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8&quo ...

  3. Intellij IDEA 14的注册码

    IntelliJ IDEA 14 注册码 IntelliJ IDEA 14 下载地址: IntelliJ IDEA 14 下载 分享几个license: (1) key:IDEA value:6115 ...

  4. 寻找序列中最小的第N个元素(partition函数实现)

    Partition为分割算法,用于将一个序列a[n]分为三部分:a[n]中大于某一元素x的部分,等于x的部分和小于x的部分. Partition程序如下: long Partition (long a ...

  5. Nginx+uWSIG+Django+websocket的实现

    1.Django+websocket django-websocket dwebsocket django-websocket是旧版的,现在已经没有人维护,dwebsocket是新版的,推荐使用dwe ...

  6. Linux_Struct file()结构体

    struct file结构体定义在/linux/include/linux/fs.h(Linux 2.6.11内核)中,其原型是:struct file {        /*         * f ...

  7. linux之vim编辑器

    Vi简介1. Vi是一种广泛存在于各种UNIX和Linux系统中的文本编辑程序.2. Vi不是排版程序,只是一个纯粹的文本编辑程序.3. Vi是全屏幕文本编辑器,它没有菜单,只有命令.4. Vi不是基 ...

  8. HBase性能优化方法总结(转)

    本文主要是从HBase应用程序设计与开发的角度,总结几种常用的性能优化方法.有关HBase系统配置级别的优化,这里涉及的不多,这部分可以参考:淘宝Ken Wu同学的博客. 1. 表的设计 1.1 Pr ...

  9. POJ1269+直线相交

    求相交点 /* 线段相交模板:判相交.求交点 */ #include<stdio.h> #include<string.h> #include<stdlib.h> ...

  10. android TabActivity的局限性 是否还有存在的必要性

     TabActivity的局限性 是否还有存在的必要性 其实谷歌有此举动,我们也应该早就想到了,为什么会这么说呢?那就要从TabActivity的原理开始说起了. 做个假定先: 比如我们最外面的Act ...