参考地址

今天看了李天平关于WinForm调用Web Service的代码,我自己模仿做一个代码基本都是复制粘贴的,结果不好使。郁闷的是,又碰到那个该死的GET调用Web Service,我想肯定又是Web.config需要配置,结果WinForm没有这个配置文件,奇怪,为什么人家的就好使,我写的就不好使呢。

上网搜吧,唉,找个两个多小时,基本都是和我一样的代码,互相转载。根本没人提代码好不好使,也没人提正确的用法。就在我要放弃的时候,终于发现原来是在 Web Service的Web.config里配置的(下面滴2步),真是欲哭无泪啊,大家可要注意啊。

好了,把过程详细说下吧。

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

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

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Services;

using System.Data;

namespace WebService1

{

/// <summary>

/// Service1 的摘要说明

/// </summary>

[WebService(Namespace = "http://tempuri.org/")]

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

[System.ComponentModel.ToolboxItem(false)]

// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。

[System.Web.Script.Services.ScriptService]

public class Service1 : System.Web.Services.WebService

{

//无参方法

[WebMethod]

public string HelloWorld()

{

return "Hello World";

}

//有参方法1

[WebMethod]

public int Add(int a, int b)

{

return a + b;

}

//有参方法2

[WebMethod]

public int Sum(int x)

{

int sum = 0;

for (int i = 0; i <= x; i++)

{

sum += i;

}

return sum;

}

// 返回一个复合类型

[WebMethod]

public  Student GetStudentByStuNo(string stuNo)

{

if(stuNo=="001")

return new Student { StuNo = "001", StuName = "张三" };

if(stuNo=="002")

return new Student { StuNo = "002", StuName = "李四" };

return null;

}

//返回返回泛型集合的

[WebMethod]

public List<Student> GetList()

{

List<Student> list = new List<Student>();

list.Add(new Student() { StuNo = "001", StuName = "张三" });

list.Add(new Student() { StuNo = "002", StuName = "李四" });

list.Add(new Student() { StuNo = "003", StuName = "王五" });

return list;

}

//返回DataSet

[WebMethod]

public  DataSet GetDataSet()

{

DataSet ds = new DataSet();

DataTable dt = new DataTable();

dt.Columns.Add("StuNo", Type.GetType("System.String"));

dt.Columns.Add("StuName", Type.GetType("System.String"));

DataRow dr = dt.NewRow();

dr["StuNo"] = "001"; dr["StuName"] = "张三";

dt.Rows.Add(dr);

dr = dt.NewRow();

dr["StuNo"] = "002"; dr["StuName"] = "李四";

dt.Rows.Add(dr);

ds.Tables.Add(dt);

return ds;

}

}

public class Student

{

public string StuNo { get; set; }

public string StuName { get; set; }

}

}

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

<webServices>

<protocols>

<add name="HttpPost" />

<add name="HttpGet" />

</protocols>

</webServices>

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

(1)选择高级

(2)选择添加web引用

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

(4)选择Service1

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

5、添加3个Windows窗体,

(1)Form1拖放的控件为:

Form1的代码为:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

namespace WinFormInvokeWebService

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

}

private void button1_Click(object sender, EventArgs e)

{

localhost.Service1 service = new localhost.Service1();

localhost.Student s = service.GetStudentByStuNo("002");

MessageBox.Show("学号:" + s.StuNo + ",姓名:" + s.StuName);

}

private void button2_Click(object sender, EventArgs e)

{

new Form2().Show();

}

private void button3_Click(object sender, EventArgs e)

{

new Form3().Show();

}

}

}

(2)Form2拖放的控件为:

Form2的代码为:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

//导入此命名空间

using System.Net;

using System.Xml;

using System.IO;

using System.Web;   //先添加System.Web引用再导入此命名空间

namespace WinFormInvokeWebService

{

public partial class Form2 : Form

{

public Form2()

{

InitializeComponent();

}

//手工发送HTTP请求调用WebService-GET方式

private void button1_Click(object sender, EventArgs e)

{

//http://localhost:3152注意你的地址可能和我的不一样,运行WebService看下你的端口改下

string strURL = "http://localhost:3152/Service1.asmx/GetStudentByStuNo?stuNo=";

strURL += this.textBox1.Text;

//创建一个HTTP请求

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);

//request.Method="get";

HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();

Stream s = response.GetResponseStream();

XmlTextReader Reader = new XmlTextReader(s);

Reader.MoveToContent();

string strValue = Reader.ReadInnerXml();

strValue = strValue.Replace("&lt;", "<");

strValue = strValue.Replace("&gt;", ">");

MessageBox.Show(strValue);

Reader.Close();

}

//手工发送HTTP请求调用WebService-POST方式

private void button2_Click(object sender, EventArgs e)

{

//http://localhost:3152注意你的地址可能和我的不一样,运行WebService看下你的端口改下

string strURL = "http://localhost:3152/Service1.asmx/GetStudentByStuNo";

//创建一个HTTP请求

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);

//Post请求方式

request.Method = "POST";

//内容类型

request.ContentType = "application/x-www-form-urlencoded";

//参数经过URL编码

string paraUrlCoded = HttpUtility.UrlEncode("stuNo");

paraUrlCoded += "=" + HttpUtility.UrlEncode(this.textBox1.Text);

byte[] payload;

//将URL编码后的字符串转化为字节

payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);

//设置请求的ContentLength

request.ContentLength = payload.Length;

//获得请求流

Stream writer = request.GetRequestStream();

//将请求参数写入流

writer.Write(payload, 0, payload.Length);

//关闭请求流

writer.Close();

//获得响应流

HttpWebResponse response = (HttpWebResponse)request.GetResponse();

Stream s = response.GetResponseStream();

XmlTextReader Reader = new XmlTextReader(s);

Reader.MoveToContent();

string strValue = Reader.ReadInnerXml();

strValue = strValue.Replace("&lt;", "<");

strValue = strValue.Replace("&gt;", ">");

MessageBox.Show(strValue);

Reader.Close();

}

}

}

(3)Form3拖放的控件为:

Form3的代码为:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

namespace WinFormInvokeWebService

{

public partial class Form3 : Form

{

public Form3()

{

InitializeComponent();

}

//利用Backgroundworker对象

private void button1_Click(object sender, EventArgs e)

{

BackgroundWorker backgroundworker = new BackgroundWorker();

// 注册具体异步处理的方法

backgroundworker.DoWork += new DoWorkEventHandler(back_DoWork);

// 注册调用完成后的回调方法

backgroundworker.RunWorkerCompleted += newRunWorkerCompletedEventHandler(back_RunWorkerCompleted);

// 这里开始异步调用

backgroundworker.RunWorkerAsync();

//调用服务的同时客户端处理并不停止

ChangeProcessBar();

}

//完成事件

void back_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)

{

if (e.Error != null)

throw e.Error;

progressBar1.Value = progressBar1.Maximum;                              //调用完成了,把客户端进度条填充满

localhost.Student s = e.Result aslocalhost.Student;                    //获取处理结果

MessageBox.Show("学号:" + s.StuNo + ",姓名:" + s.StuName);            //显示从服务器获取的结果值

}

//调用方法

void back_DoWork(object sender, DoWorkEventArgs e)

{

// Web Service代理类

localhost.Service1 service = new localhost.Service1();

// 调用Web方法GetClass1,结果赋值给DoWorkEventArgs的Result对象

e.Result = service.GetStudentByStuNo("002");

}

/// <summary>

/// 界面的进度条显示

/// </summary>

void ChangeProcessBar()

{

for (int i = 0; i < 10; i++)

{

progressBar1.Value = i;

System.Threading.Thread.Sleep(500);

}

}

//调用WebMethod的Async方法

private void button2_Click(object sender, EventArgs e)

{

// Web Service代理类

localhost.Service1 service = new localhost.Service1();

//这里开始异步调用

//service.GetProductPriceAsync("001");

service.GetStudentByStuNoAsync("002");

// 注册调用完成后的回调方法

service.GetStudentByStuNoCompleted += newlocalhost.GetStudentByStuNoCompletedEventHandler(GetStudentByStuNoCompleted);

//调用同时客户端处理不停止

ChangeProcessBar();

}

//完成事件

void GetStudentByStuNoCompleted(object sender, localhost.GetStudentByStuNoCompletedEventArgse)

{

if (e.Error != null)

throw e.Error;

progressBar1.Value = progressBar1.Maximum;                              //调用完成了,把客户端进度条填充满

localhost.Student s = e.Result aslocalhost.Student;                    //获取处理结果

MessageBox.Show("学号:" + s.StuNo + ",姓名:" + s.StuName);            //显示从服务器获取的结果值

}

}

}

运行结果:

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

    1.建立项目WebService和WinForm项目,这里起名为WinFormInvokeWebService,如图所示, 2.Service1.asmx代码为:(这部分其实和上篇的代码是一样的) u ...

  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. Eclipse——浏览功能

    一,打开变量声明 或选择opendeclaration就能够查看变量的定义 二.打开类型层次结构(open type hierarchy) 或者点击F4 watermark/2/text/aHR0cD ...

  2. 关于mysql的wait_timeout参数 设置不生效的问题

    关于wait_timeout 有一次去online set wait_timeout 的时候发现改了不生效,如下: mysql> show variables like 'wait_timeou ...

  3. CVPR14 图像检索papers

    CVPR14年关于图像检索方面的papers,汇总成一个list,方便阅读. 图像检索 Triangulation embedding and democratic aggregation for i ...

  4. Android开发之Navigationdrawer导航抽屉功能的实现(源码分享)

    导航抽屉(navigationdrawer)是一个从屏幕左边滑入的面板,用于显示应用的主要导航项目.用户能够通过在屏幕左边缘滑入或者触摸操作栏的应用图标打开导航抽屉. 导航抽屉覆盖在内容之上,但不覆盖 ...

  5. iOS开发-多线程简介

    多线程从概念上理解是指从软件或者硬件上实现多个线程并发执行的技术,简单点理解就是同一时间可以执行多个事情(比如说一边听歌一边码代码),听歌是一个线程,码代码是一个线程,如果是单核CPU的话,上面两个动 ...

  6. Linked List Cycle leetcode II java (寻找链表环的入口)

    题目: Given a linked list, return the node where the cycle begins. If there is no cycle, return null. ...

  7. IE6的3像素神奇bug:缘起与解决方案

    在我们这样一个神奇的国度,到了2014年了,居然还是有很多人的电脑上用着XP,安装的是IE6,他们没有想过要升级,我们就得想着兼容他们.... 一. 6爷我喝高了,最后一行有重影.那什么是IE6 的3 ...

  8. 【SpringCloud】Netflix源码解析之Ribbon:负载均衡策略的定义和实现

    Ribbon负载均衡策略定义 IRule其实就只做了一件事情Server choose(Object key),可以看到这个功能是在LB中定义(要求)的,LB把这个功能委托给IRule来实现.不同的I ...

  9. 转: Nginx proxy讲解精华文章集

    1. 详细,参数说明很好 https://blog.lyz810.com/article/2016/06/ngx_stream_proxy_module_doc_zh-cn/

  10. (转)NGUI系列教程七(序列帧动画UITexture 和 UIsprit)

    NGUI系列教程七(序列帧动画)   今天我给大家讲一下如何使用NGUI做序列帧动画.本节主要包括两方面内容,分别是使用UIspirit和使用UITexture 做序列帧动画.废话不说了,下面开始.还 ...