微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

WindowsForm应用程序调用WebService

本文原创,如需转载,请标明源地址,谢谢合作!http://blog.csdn.net/sue_1989/article/details/6597078

 

本文的编写IDE为VSTS2008和.NET Framework3.5 ,其他版本的VS或.Net Framework类似

本示例程序说明:从WinForm程序调用本机的WebServices的方法,返回两个数的和

1. 新建>>项目>>ASP.NET Web 服务应用程序,命名为 WebServiceTest,OK

2.打开Service1.asmx.cs,   添加方法 Add(),请注意方法前的 [WebMethod(Description="Add")]  为必须。

[csharp]  view plain copy print ?
  1. namespace WebServiceTest  
  2. {  
  3.     /// <summary>  
  4.     /// Service1 的摘要说明  
  5. /// </summary>  
  6.     [WebService(Namespace = "http://tempuri.org/")]  
  7.     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]  
  8.     [ToolBoxItem(false)]  
  9. // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。  
  10. // [System.Web.Script.Services.ScriptService]  
  11.     public class Service1 : System.Web.Services.WebService  
  12.     {  
  13.   
  14.         [WebMethod]  
  15.         public string HelloWorld()  
  16.         {  
  17.             return "Hello World"+"world hello";  
  18.         }  
  19.         [WebMethod(Description="Add")]  
  20.         public int add(int x,int y)  
  21.             return x + y;  
  22.     }  
  23. }  


 

3.启动程序,浏览器器会自动启动,如下图表示WebService正常启动

 注意浏览器的URL,这个将在后面的应用程序中引用时作为地址,很重要

4. 点击Add,进入调用,分别输入参数x,y的值,点击调用,浏览器会跳转显示如下的XML(一般情况下会在浏览器中显示XML文本)

 

5.以上步骤表示我们建立的WebService可以正常使用,现在可以不停止此程序的调试,即暂时不关闭此服务的运行,暂时放一边不管它

6. 另打开一个VS,新建>>项目>>Windows窗体应用程序,命名为WindowsFormsApplicationTest>>OK

7.添加控件,三个TextBox,两个Lable,一个Button

8.引用刚才建立的WebService到这个项目

  右键点击解决方案管理器中的项目,选择“添加服务引用”,弹出如下对话框

 输入刚才的WebServices的地址,点击前往,添加Service1Soap,把 命名空间改为 WebServiceTest,确定,就会生成如下的引用,现在就可以使用这个WebService了

结果:

9.添加Button的事件处理

?
    namespace WindowsFormsApplicationTest  
  1.     public partial class mainForm : Form  
  2.           
  3.         public mainForm()  
  4.             InitializeComponent();   
  5.         private void btnPlus_Click(object sender, EventArgs e)  
  6.         {  
  7.             int var1=int.Parse(this.textBox1.Text);  
  8.             int var2=int.Parse(this.textBox2.Text);  
  9.             WebServiceTest.Service1SoapClient ws = new WebServiceTest.Service1SoapClient();  
  10.             int result=ws.add(var1, var2);  
  11.             this.textBox3.Text = result.ToString();  
  12.               
  13.           
  14.          
  15.     }  
  16. }  

上面的处理中用到的string和int型的互转这里就不解释了

关键方法是WebServiceTest.Service1SoapClient ws = new WebServiceTest.Service1SoapClient()

10. 运行

输入数据,点击就OK了

其他的WebService方法大家也可以自己试试。

如果遇到报错说服务没有或异常,是因为WebService的服务没有启动,在第一个程序中其中就行。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐