转载:http://www.cnblogs.com/yycxbjl/archive/2010/04/20/1716689.html

 

 

PS: 开发工具 VS2010, 所有工程都为Debug状态,!

                                                                                                   

一、创建Web Service 工程

1. 新建一个 Web Service 工程,工程名为WebServiceProject

File -> New -> Project  -->   Visual C# -> Web -> ASP.NET Web Service Application

注意: .NET Framework版本选3.5, 4.0 中没有该类型的工程

 

2. 在WebServiceProject中,删除 Servie1 类中原有的HelloWorld方法,添加一个方法 ReverseString 

代码
按 Ctrl+C 复制代码

必须加上在方法前加上 [WebMethod] 属性

方法中首行的 Sleep(5000) 为了展示下文中同步调用与异步调用 Web Service中方法的区别

 

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

改为 [WebService(Namespace = "http://WebServiceSample/")]     名字随便取

可以不改,若不改,下一步通过浏览器查看时会有提示(可以自己看一下)

 

3. 编译并测试WebServiceProject

按 F7编译工程,通过浏览器查看Servic1.asmx

 

由于工程中只有一个方法,页面显示如下:

点击ReverseString,可以进入该方法的测试页面,进行测试

 

 

二、部署Web Service

1.  发布工程到本地的某一个目录(D:\WebServiceSample)

 

  
 2. 发布完后,在IIS中添加一个指向该目录的虚拟目录(或应用程序)

 3. 通过 浏览器 查看,测试发布是否成功

http://localhost/webservicesample/service1.asmx

页面显示应与上一节中相同

 

三、使用Web Service

1.  使用WSDL 工具生成 Web Service 中 Servie1类的代理类

     打开 VS2010 命名行工具

 

输入如下命名,在D:\生成一个myProxyClass.cs文件,里面有一个代理类

public partial class Service1 : System.Web.Services.Protocols.SoapHttpClientProtocol

关于如何生成代理类的详见

http://msdn.microsoft.com/zh-cn/library/7h3ystb6.aspx 

 

 

2. 新建一个Windows Form Application,来使用Web Service,工程名为 WebServiceClient

   在工程中添加步骤1中生成的myProxyClass.cs文件

   添加 System.Web.Services引用:Project -> Add Reference

 

3. 在Form1上,拖入几个控件

 

4.  为按钮添加事件响应函数

     
     
<!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ --> // 同步 private void button1_Click( object sender, EventArgs e) { Service1 ws = new Service1(); textBox2.Text = ws.ReverseString(textBox1.Text); } // 异步 private void button2_Click( object sender, EventArgs e) { Service1 ws = new Service1(); ws.ReverseStringCompleted += new ReverseStringCompletedEventHandler(ReverseStringCompleted); ws.ReverseStringAsync(textBox1.Text); } private void ReverseStringCompleted( object sender, ReverseStringCompletedEventArgs e) { textBox2.Text = e.Result; }

 

5.  测试程序的效果

用同步响应时,在Web Service中的方法结束前,程序无法响应

用异步响应时,在Web Service中的方法结束前,程序可以响应

 

------------

需了解的地方:

1)使用web service引用和用wsdl生成的区别是什么?

其中使用wsdl生成,web service  服务也必须存在。

2)是否使用wsdl编译后,是否还生成异步的过程?