65.9K
CodeProject 正在变化。 阅读更多。
Home

Web Services,一种简单的方法

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.58/5 (32投票s)

2006年3月24日

CPOL

5分钟阅读

viewsIcon

124966

downloadIcon

1534

本文是对 Web Services 的介绍,并附有简单的说明。

摘要

万维网越来越多地用于应用程序之间的通信。提供的编程接口被称为 Web Services。广义上的“Web Services”标签有两种含义——一种是具体的,另一种是概念性的。.NET 是微软开发的分布式计算平台,ASP.NET 是其用于 Web 开发的编程模型。随着 .NET 和 .NET Framework 的出现,微软引入了一系列新的技术,包括 Web Services 和 .NET Remoting。ASP.NET Web Services 是一项强大的技术,它为开发分布式应用程序提供了合适的框架。

解决方案概述

这一系列文章的主要思想不是让您感觉像是在学习一项全新的技术,而是让您认识到这项创新是通过重用现有知识来在 Web 世界中创建更强大、更健壮的系统。基本上,本文旨在学习什么是 Web Service,如何在 .NET 中创建 Web Service,如何使用 Web Service 访问数据库,如何使用 Web Service 填充 GridView 等等。

让我们先看看什么是 Web Service。Web Services 是松散耦合的、可重用的软件组件,它们在语义上封装了离散的功能,并且可以通过标准的 Internet 协议进行分布式访问和编程访问。

具体来说,Web Services 是一系列新兴标准,它们描述了面向服务的、基于组件的应用程序架构。

从概念上讲,Web Services 代表了一种模型,其中电子商务流程中的离散任务广泛分布在价值网络中。

标准

核心 Web Services 标准包括

  • 简单对象访问协议 (SOAP),
  • Web Services 描述语言 (WSDL),以及
  • 通用描述、发现和集成 (UDDI)

SOAP 基于 XML,而不是像 DCOM 这样的二进制协议。您可以使用网络隧道工具详细检查数据交换,并确切地了解底层发生了什么。

XML Web Services 是 Internet 上分布式计算的根本构建块。开放标准以及人与应用程序之间通信和协作的重点,创造了一个 XML Web Services 成为应用程序集成平台的环境。

WSDL(通常发音为“whiz-dull”)代表 Web Services Description Language。WSDL 是一种 XML 格式,用于将网络服务描述为一组端点,这些端点操作包含面向文档或面向过程信息的消息。WSDL 对于 SOAP 来说,就像 IDL 对于 CORBA 或 COM 一样。由于 WSDL 是 XML,因此它是可读和可编辑的,但在大多数情况下,它是由软件生成和使用的。

此应用程序中使用的控件

protected System.Web.UI.WebControls.GridView GridView1;

此应用程序中使用的命名空间

using System.Web.Services;
using System.Web.Services.Protocols;
using System.Runtime.InteropServices;
using System.Configuration;
using System.Diagnostics;
using System.EnterpriseServices;
using System.Xml;

带有代码的解决方案

使用 Visual Studio .NET 创建 Web Service 是最简单的任务之一。通过使用 Visual Studio .NET 的向导,您可以在一分钟内创建您的 Web Service 项目。创建 Web Service 项目后,编写一个简单的函数来测试您的 Web Service。在本例中,我编写了一个名为 DisplayTextMsg() 的简单公共函数,它将输出一个字符串。

// Simple method :: This return a string 
[WebMethod]
public string DisplayTextMsg() 
{
    return "My First Service For Testing";
}

将 WebMethod 属性附加到公共函数表明您希望该函数作为 XML Web Service 的一部分公开。WebMethod 属性提供以下属性:

  • BufferResponse - WebMethod 属性的 BufferResponse 属性启用 XML Web Service 方法响应的缓冲。
  • CacheDuration - WebMethod 属性的 CacheDuration 属性启用 XML Web Service 方法结果的缓存。
  • Description - WebMethod 属性的 Description 属性为 XML Web Service 方法提供一个描述,该描述将显示在服务帮助页面上。
  • EnableSession - WebMethod 属性的 EnableSession 属性为 XML Web Service 方法启用会话状态。
  • MessageName - WebMethod 属性的 MessageName 属性允许 XML Web Service 使用别名唯一地标识重载的方法。
  • TransactionOption - WebMethod 属性的 TransactionOption 属性允许 XML Web Service 方法作为事务的根对象参与其中。

数据库访问方法

现在,让我们编写一个简单的函数来连接数据库并获取数据,然后将其作为 XML 文档返回。我已将该函数编写如下:

// Simple method to access database :: This return a xml Document
[WebMethod]
public XmlDocument GetDataFromDB()
{
    string errorMessage = "";
    XmlDocument myDatas = new XmlDocument();
    //Connection string is stored 
    //in the web.config file as an appSetting
    string connectionString = 
      ConfigurationSettings.AppSettings["DatabaseConnectionString"];
    SqlConnection dbConnection = null;
    // Open a connection to the database
    try
    {
        dbConnection = new SqlConnection(connectionString);
        dbConnection.Open();
    }
    catch (Exception ex)
    {
        errorMessage = ex.Message;
    }
    if (errorMessage == "")
    {
        // Build an insert command
        string SQL = "select * From ProfileContact";
        SqlCommand GetCustomerCmd = new SqlCommand(SQL, dbConnection);

        try
        {
            SqlDataAdapter custDA = new SqlDataAdapter();
            custDA.SelectCommand = GetCustomerCmd;
            DataSet custDS = new DataSet();
            custDA.Fill(custDS, "ProfileContact");
            myDatas.LoadXml(custDS.GetXml());
            dbConnection.Close();
           
        }
        catch (System.Exception ex)
        {
            errorMessage = ex.Message;

        }
        finally
        {
            dbConnection.Dispose();
        }
    }
    return myDatas;
}

编写完这些函数后,让我们看看如何在我们的 ASP.NET Web 应用程序中访问此 Web Service。首先,创建一个新的 Web 应用程序。在解决方案资源管理器窗口中,右键单击“引用”并选择“添加 Web 引用”。在“添加 Web 引用”窗口中,输入您的 Web Service 的路径(https://:2034/WebServices/Service.asmx)。然后,单击“添加引用”按钮。

现在,让我们看看如何在您的 ASP.NET 网页中调用 WebMethod。首先,在您的类中初始化 Web Service。

localhost.Service myService1 = new localhost.Service();

初始化 Web Service 后,您就可以在 ASP.NET 页面中调用该 Web Service 的 WebMethod。首先,让我们看看如何在 ASP.NET 页面中调用 DisplayTextMsg()。在这里,我在按钮单击事件中调用此 WebMethod。

// Button Click Event 
protected void Button1_Click(object sender, EventArgs e)
{
    string serMsg = myService1.DisplayTextMsg();
    lbl_display.Text = serMsg.ToString();
}

上面的代码片段是一个简单的演示。

让我们看看如何使用 Web Service 填充 GridView 控件。在此演示中,Web Service 将访问数据库,然后填充 GridView。WebMethod GetDataFromDB() 将返回一个 XML 文档。我将此 XML 文档插入到 DataSet 中,然后将生成的 Dataset 填充到 GridView 中。

// Data Binding :: DataSet Appending
public void DataBindFrmWS()
{
   XmlDocument myServiceDoc = new XmlDocument();
   System.Xml.XmlNode neNode;
   //Adding the resulting XML from WebMethod to a user created XmlNode
   neNode = myService1.GetDataFromDB();
   //Creating a Dataset
   DataSet myDataSet = new DataSet();
   //The XmlNode is added to a byte[]
   byte[] buf = System.Text.ASCIIEncoding.ASCII.GetBytes(neNode.OuterXml);
   System.IO.MemoryStream ms = new System.IO.MemoryStream(buf);
   //The XML is readed from the MemoryStream
   myDataSet.ReadXml(ms);
   
   GridView1.DataSource = myDataSet.Tables[0];
   GridView1.DataBind();
}

上面的代码片段将使用来自 Web Service 的数据来填充您的 GridView 控件。

现在,您可以构建自己的 Web Service,并在任何您想要的应用程序中使用它。

这是一个显示 Web Services 如何工作的简单参考图。

摘要

本文旨在初步引导您掌握 Web Services 的技能,绝非 Web Services 功能的完整列表。但这只是一个开始,它应该能帮助您在短时间内构建使用 Web Services 的分布式应用程序。Visual Studio .NET 向导将帮助您轻松快速地开发 Web Services。

© . All rights reserved.