目录

ASP.NET - Web服务( Web Services)

Web服务是使用Web应用程序使用的Web协议访问的基于Web的功能。 Web服务开发有三个方面:

  • 创建Web服务
  • 创建代理
  • 使用Web服务

创建Web服务

Web服务是一个Web应用程序,它基本上是一个由其他应用程序可以使用的方法组成的类。 它还遵循代码隐藏架构,例如ASP.NET网页,尽管它没有用户界面。

为了理解这个概念,让我们创建一个Web服务来提供股票价格信息。 客户可以根据股票代码查询股票的名称和价格。 为了使这个例子简单,这些值在二维数组中被硬编码。 此Web服务有三种方法:

  • 默认的HelloWorld方法
  • GetName方法
  • 一个GetPrice方法

执行以下步骤以创建Web服务:

Step (1) :在Visual Studio中选择文件 - “新建 - ”网站,然后选择“ASP.NET Web服务”。

Step (2) :在项目的App_Code目录中创建名为Service.asmx的Web服务文件及其代码隐藏文件Service.cs。

Step (3) :将文件名更改为StockService.asmx和StockService.cs。

Step (4) :.asmx文件上只有一个WebService指令:

<%@ WebService Language="C#" CodeBehind="~/App_Code/StockService.cs" Class="StockService" %>

Step (5) :打开StockService.cs文件,其中生成的代码是基本的Hello World服务。 后台文件的默认Web服务代码如下所示:

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
namespace StockService
{
   // <summary>
   // Summary description for Service1
   // <summary>
   [WebService(Namespace = "http://tempuri.org/")]
   [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
   [ToolboxItem(false)]
   // To allow this Web Service to be called from script, 
   // using ASP.NET AJAX, uncomment the following line. 
   // [System.Web.Script.Services.ScriptService]
   public class Service1 : System.Web.Services.WebService
   {
      [WebMethod]
      public string HelloWorld()
      {
         return "Hello World";
      }
   }
}

Step (6) :更改文件后面的代码,为股票代码,名称和价格添加二维字符串数组,以及获取股票信息的两种网络方法。

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)]
// To allow this Web Service to be called from script, 
// using ASP.NET AJAX, uncomment the following line. 
// [System.Web.Script.Services.ScriptService]
public class StockService : System.Web.Services.WebService
{
   public StockService () {
      //Uncomment the following if using designed components 
      //InitializeComponent(); 
   }
   string[,] stocks =
   {
      {"RELIND", "Reliance Industries", "1060.15"},
      {"ICICI", "ICICI Bank", "911.55"},
      {"JSW", "JSW Steel", "1201.25"},
      {"WIPRO", "Wipro Limited", "1194.65"},
      {"SATYAM", "Satyam Computers", "91.10"}
   };
   [WebMethod]
   public string HelloWorld() {
      return "Hello World";
   }
   [WebMethod]
   public double GetPrice(string symbol)
   { 
      //it takes the symbol as parameter and returns price
      for (int i = 0; i < stocks.GetLength(0); i++)
      {
         if (String.Compare(symbol, stocks[i, 0], true) == 0)
         return Convert.ToDouble(stocks[i, 2]);
      }
      return 0;
   }
   [WebMethod]
   public string GetName(string symbol)
   {
      // It takes the symbol as parameter and 
      // returns name of the stock
      for (int i = 0; i < stocks.GetLength(0); i++)
      {
         if (String.Compare(symbol, stocks[i, 0], true) == 0)
         return stocks[i, 1];
      }
      return "Stock Not Found";
   }
}

Step (7) :运行Web服务应用程序提供Web服务测试页面,允许测试服务方法。

股票服务

Step (8) :单击方法名称,检查其是否正常运行。

获取姓名

Step (9) :为了测试GetName方法,提供其中一个硬编码的股票代码,它返回股票的名称

股票的名称

使用Web服务

要使用Web服务,请在同一解决方案下创建网站。 这可以通过在解决方案资源管理器中右键单击解决方案名称来完成。 调用Web服务的Web页面应该有一个标签控件来显示返回的结果,两个按钮控件用于回发,另一个用于调用服务。

Web应用程序的内容文件如下:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="wsclient._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
   <head runat="server">
      <title>
         Untitled Page
      </title>
   </head>
   <body>
      <form id="form1" runat="server">
         <div>
            <h3>Using the Stock Service</h3>
            <br /> <br />
            <asp:Label ID="lblmessage" runat="server"></asp:Label>
            <br /> <br />
            <asp:Button ID="btnpostback" runat="server" onclick="Button1_Click" Text="Post Back" style="width:132px" />
            <asp:Button ID="btnservice" runat="server" onclick="btnservice_Click"  Text="Get Stock" style="width:99px" />
         </div>
      </form>
   </body>
</html>

Web应用程序的代码隐藏文件如下:

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
//this is the proxy
using localhost;
namespace wsclient
{
   public partial class _Default : System.Web.UI.Page
   {
      protected void Page_Load(object sender, EventArgs e)
      {
         if (!IsPostBack)
         {
            lblmessage.Text = "First Loading Time: " +  DateTime.Now.ToLongTimeString
         }
         else
         {
            lblmessage.Text = "PostBack at: " + DateTime.Now.ToLongTimeString();
         }
      }
      protected void btnservice_Click(object sender, EventArgs e)
      {
         StockService proxy = new StockService();
         lblmessage.Text = String.Format("Current SATYAM Price:{0}",
         proxy.GetPrice("SATYAM").ToString());
      }
   }
}

创建代理

代理是Web服务代码的替代品。 在使用Web服务之前,必须创建代理。 代理已在客户端应用程序中注册。 然后,客户端应用程序使用本地方法调用Web服务。

代理接受调用,以适当的格式包装它,并将其作为SOAP请求发送到服务器。 SOAP代表简单对象访问协议。 该协议用于交换Web服务数据。

当服务器将SOAP包返回给客户端时,代理会解码所有内容并将其呈现给客户端应用程序。

在使用btnservice_Click调用Web服务之前,应该将Web引用添加到应用程序。 这将透明地创建一个代理类,由btnservice_Click事件使用。

protected void btnservice_Click(object sender, EventArgs e)
{
   StockService proxy = new StockService();
   lblmessage.Text = String.Format("Current SATYAM Price: {0}", 
   proxy.GetPrice("SATYAM").ToString());
}

按照以下步骤创建代理:

Step (1) :右键单击解决方案资源管理器中的Web应用程序条目,然后单击“添加Web引用”。

添加Web引用

Step (2) :选择“此解决方案中的Web服务”。 它返回StockService引用。

选择Web服务

Step (3) :单击该服务将打开测试网页。 默认情况下,创建的代理称为“localhost”,您可以重命名它。 单击“添加引用”以将代理添加到客户端应用程序。

股票服务2

通过添加以下内容将代理包含在代码隐藏文件中:

 using localhost;
↑回到顶部↑
WIKI教程 @2018