Web Service 简单应用,创建及调用过程(图文)

(一)  WebService 应用的创建
首先,打开VS2005,打开"文件-新建-网站",选择"ASP.NET Web服务"
未命名

查看Service.cs代码,你会发现VS.Net 2005已经为Web Service文件建立了缺省的框架。原始代码为:


using System; using System.Linq; using System.Web; using System.Web.Services; using System.Web.Services.Protocols; using System.Xml.Linq; [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。 // [System.Web.Script.Services.ScriptService] public class Service : System.Web.Services.WebService { public Service() { //如果使用设计的组件,请取消注释以下行 //InitializeComponent(); } [WebMethod] public string HelloWorld() { return "Hello World"; } }

可直接运行 Service.asmx 查看,效果如下:
1
点击它可以进行调用这个默认的 HelloWorld 方法,返回一个 XML 格式的结果,说明我们的这个简单 WebService 环境正常.

现在,我们手动向 Service.cs 类中添加一个简单的求和方法,代码如下:

using System;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
// [System.Web.Script.Services.ScriptService]
public class Service : System.Web.Services.WebService
{
    public Service()
    {
        //如果使用设计的组件,请取消注释以下行 
        //InitializeComponent(); 
    }

    [WebMethod]
    public string HelloWorld()
    {
        return "Hello World";
    }

    [WebMethod(Description="两个整数的求和")]
    public int Sum(int a,int b)
    {
        return a + b;
    }
}

这里要注意的是, 如果我们写了一个函数,并希望此函数成为外部可调用的接口函数,我们必须在函数上面添上一行代码[WebMethod(Description="函数的描述信息")],如果你的函数没有这个申明,它将不能被用户引用.
注1: Description="函数的描述信息" 这一段可以省略,不会影响方法被调用,不过一般会补上方法的简略介绍.
注2: Service 类中也是可以包含不被外界所调用的方法的,这点不要混淆.


运行后效果如下:

2

点击 Sum 会出现下图:
3
输入 a,b 的值并调用后,返回 XML 形式的结果页面.
4
至此,创建一个简单的 WebService 应用已经完成,只须将其在服务器上发布,就可以被用户调用了.

(二)  WebService 应用的调用
无论是创建 WinForm 应用程序或是 ASP.NET 应用程序,调用 WebService 服务都是非常简单的,步骤和要点如下:

  1. 在服务器上发布这个创建好的 Web 应用,例如在本机的 IIS 上配置这个新的 Web 服务,如图:
    11
  2. 在资源管理器的工程中点击右键,选择添加 Web 引用,找到目标服务,点击 添加应用.
    111
    1
  3. 添加成功后在工程中如图:
    2
  4. 必须实例化 Web 服务,才能调用 Web 方法.本例中后台代码调用 Web 方法如下:

    public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { btnDo.Click += new EventHandler(btnDo_Click); } void btnDo_Click(object sender, EventArgs e) { localhost.Service S = new localhost.Service(); txtResult.Text = S.Sum(Convert.ToInt32(txtNum1.Text), Convert.ToInt32(txtNum2.Text)).ToString(); } }
原文地址:https://www.cnblogs.com/SkySoot/p/2258787.html