ASP.NET Web Service 创建、部署与使用

PS: 开发工具 VS2010, 所有工程都为Debug状态,本人刚接触 Web Service,此文为菜鸟入门用例,高手勿笑!

转载请注明出处                                                                                                                  

一、创建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 

代码
   
   
[WebMethod]
public string ReverseString( string s)
{
System.Threading.Thread.Sleep(
5000 );
char [] a = s.ToCharArray();
Array.Reverse(a);
return new string (a);
}

必须加上在方法前加上 [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.  为按钮添加事件响应函数

  
  
// 同步
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中的方法结束前,程序可以响应

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值