2.1首先创建一个最基本的web service服务端,顾名思义就是提供服务,这儿实现一个简单的加法计算。
首先,vs2013--文件---新建项目---Asp.net 空Web 应用程序 (VC# 下面的)
创建 名称 ServiceFuwuduan ----名字自己去就可以啦
生成项目如图所示的解决方案和项目
然后在项目上 点击右键 ---添加---新建项 弹出新窗口----找到Web服务(asms)
生成的ServiceFuwu.asmx 代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; namespace ServiceFuwuduan { /// <summary> /// ServiceFuwu 的摘要说明 /// </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 ServiceFuwu : System.Web.Services.WebService { [WebMethod] public string HelloWorld() { return "Hello World"; } } }
在该文件下,编写加法的实现代码如下:
[WebMethod] public int Add(int x, int y) { int sum; sum = x + y; return sum; }
该项目编写完毕,项目右键----发布---选择文件系统
2.2将该项目在IIS 中发布
如图所示,服务端正常运行,地址为:http://localhost:9007/ServiceFuwu.asmx
2.3 开发web service 客户端程序
新建项目 vs2013--文件---新建项目---Asp.net 空Web 应用程序 (VC# 下面的)
然后,添加一个Web窗体:
项目文件夹:
其中Default.aspx 前端代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="GetService.Default" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> </head> <body> <form id="form1" runat="server"> <div> </div> </form> </body> </html>
添加加法的 表单:
<body> <form id="form1" runat="server"> <div> 第一:<asp:TextBox ID="txtValue1" runat="server"></asp:TextBox> <br/> 第二:<asp:TextBox ID="txtValue2" runat="server"></asp:TextBox> <br /> 求和:<asp:TextBox ID="txtSum" runat="server"></asp:TextBox> <br /> <asp:Button ID="btnOK" runat="server" Text="WEbdd" OnClick="btnOK_Click" /> </div> </form> </body>
下面添加 服务引用:
项目右键---添加----服务引用---
输入上面的服务端地址 左下角有个命名空间,自己写个名字就行,这儿是KissSu
服务引用以后,会在当前项目 生成相应的代码:
此时生成下解决方案,没有问题
下面编写default.aspx.cs 中的代码,实现向服务端发送数值,实现功能:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace GetService { public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } //以下代码为手动编写, protected void btnOK_Click(object sender, EventArgs e) { KissSu.ServiceFuwuSoapClient ss = new KissSu.ServiceFuwuSoapClient(); int i = Convert.ToInt32(txtValue1.Text); int j = Convert.ToInt32(txtValue2.Text); txtSum.Text = ss.Add(i, j).ToString(); } //以上代码为手动编写,其他为自动生成 } }
直接运行此项目: