ASP.NET Web 服務(wù)

2018-03-19 15:28 更新

Web 服務(wù)

Web 服務(wù)是一個(gè)基于網(wǎng)絡(luò)的功能,可被 web 應(yīng)用通過 web 網(wǎng)絡(luò)協(xié)議獲取。web 服務(wù)開發(fā)主要包含以下三方面:

  • 創(chuàng)建 web 服務(wù)
  • 創(chuàng)建代理服務(wù)器
  • 使用 web 服務(wù)

創(chuàng)建 web 服務(wù)

一個(gè) web 服務(wù)就是一個(gè) web 應(yīng)用,基本形式為一個(gè)類包含可以被其他應(yīng)用調(diào)用的多個(gè)方法,它也采用隱藏代碼結(jié)構(gòu)例如 ASP.NET 網(wǎng)頁,但它不存在用戶接口。

為了更好地理解這個(gè)概念讓我們創(chuàng)建一個(gè)提供股票價(jià)格信息的 web 服務(wù)。該服務(wù)的客戶端可以通過股票的標(biāo)簽查詢相關(guān)的名字和價(jià)格。為了簡化這個(gè)例子,我們設(shè)置股票價(jià)格為固定值,保存在一個(gè)二維列表中。這個(gè) web 服務(wù)包含三個(gè)方法:

  • 一個(gè)默認(rèn)的 HelloWorld 方法
  • 一個(gè) GetName 方法
  • 一個(gè) GetPrice 方法

采取以下步驟創(chuàng)建該服務(wù):

步驟 (1) : 在 Visual Studio 中選擇 File -> New -> Web Site,然后選擇 ASP.NET Web Service。

步驟 (2) : 一個(gè)名為 Service.asmx 的 web 服務(wù)文件和它的代碼被隱藏,Service.cs 會(huì)在這個(gè)工程的 App_Code 路徑下被創(chuàng)建。

步驟 (3) : 將文件名修改為 StockService.asmx 和 StockService.cs。

步驟 (4) : .asmx 文件簡化了一個(gè) WebService 指令如下:

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

步驟 (5) : 打開 StockService.cs 文件,在該文件里生成的代碼是 Hello World 服務(wù)的基礎(chǔ)代碼。默認(rèn)的 web 服務(wù)代碼如下:

    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";
          }
       }
    }

步驟 (6) : 修改文件內(nèi)的代碼增加一個(gè)存儲(chǔ)了各股票標(biāo)簽,名稱和價(jià)格的字符串的二維指針,并編寫獲取股票信息的兩個(gè) web 方法如下;

    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";
       }
    }

步驟 (7) : 運(yùn)行 web 服務(wù)應(yīng)用給出了一個(gè) web 服務(wù)測試頁面,我們可以在該頁面測試服務(wù)方法。

步驟 (8) : 點(diǎn)擊一個(gè)方法名字,確認(rèn)它是否在正確運(yùn)行。

步驟 (9) : 為檢測 GetName 方法,提供已經(jīng)被定義的股票標(biāo)簽中的一個(gè),正確的話會(huì)返回相關(guān)股票的名稱。

使用 Web 服務(wù)

為使用該 web 服務(wù),我們在相同的解決方案(Solution)下創(chuàng)建一個(gè)網(wǎng)站,只需在解決方案管理器上右擊該解決方案名字即可,web 服務(wù)調(diào)用的網(wǎng)頁應(yīng)具有一個(gè)控制管理以顯示返回的結(jié)果和兩個(gè)控制按鈕,一個(gè)用于返回另一個(gè)用于開始調(diào)用服務(wù)。

web 應(yīng)用的文件內(nèi)容如下:

    <%@ 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 應(yīng)用的代碼如下:

    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());
           }
      }
    }

創(chuàng)建代理服務(wù)器

代理服務(wù)器指的是一個(gè) web 服務(wù)代碼的代替者。在使用 web 服務(wù)之前,我們必須創(chuàng)建一個(gè)代理服務(wù)器。這個(gè)代理服務(wù)器是由客戶端應(yīng)用注冊的。然后客戶端應(yīng)用實(shí)現(xiàn)調(diào)用 web 服務(wù)使之像在使用一個(gè)本地方法一樣。

該代理服務(wù)器將調(diào)用,并用適當(dāng)?shù)母袷綄⒄{(diào)用像發(fā)送 SOAP 請求一樣發(fā)送到服務(wù)器。SOAP 支持簡單對象訪問協(xié)議(Simple Object Access Protocol)。該協(xié)議適用于 web 服務(wù)數(shù)據(jù)交換。

當(dāng)此服務(wù)器響應(yīng)并返回一個(gè) SOAP 包給客戶端時(shí),代理服務(wù)器將一切呈現(xiàn)給客戶端應(yīng)用程序。

使用 btnservice_click 調(diào)用 Web 服務(wù)之前,Web 應(yīng)用應(yīng)該被添加到應(yīng)用程序。這將透明地創(chuàng)建一個(gè)代理類,可由 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());
    }

采取以下步驟創(chuàng)建代理:

步驟 (1) : 在解決方案管理器(SolutionExplorer)的 web 應(yīng)用入口處右擊選擇 ‘Add Web Reference’。

步驟 (2) : 選擇 ‘Web Services in this solution’,會(huì)返回我們編寫的股票服務(wù)引用。

步驟 (3) : 點(diǎn)擊該服務(wù)打開測試頁面,創(chuàng)建代理時(shí)默認(rèn)為 ‘localhost’,當(dāng)然你也可以進(jìn)行重命名。點(diǎn)擊 ‘Add Reference’ 來實(shí)現(xiàn)向客戶端應(yīng)用程序添加一個(gè)代理。

在代碼中加入以下語句使之包含該代理:

using localhost;
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)