共用方式為


逐步解說:建立和使用具備 AJAX 能力的 Web 服務

更新:2007 年 11 月

Visual Studio 2008 和 Microsoft Visual Web Developer Express 版可讓您建立可從用戶端指令碼存取的 ASP.NET 自訂 Web 服務 (.asmx 檔案)。在本逐步解說中,您要建立具備 AJAX 能力的 Web 服務,並使用用戶端指令碼呼叫其方法。

當您建立 ASP.NET Web 服務並向用戶端指令碼公開時,ASP.NET 會自動建立 Web 服務的 JavaScript Proxy 類別。您可以呼叫 JavaScript Proxy 類別對應的方法,藉此呼叫 Web 服務方法。

本逐步解說示範:

  • 如何在 Visual Studio 2008 或 Microsoft Visual Web Developer Express 版中建立具備 AJAX 能力的 Web 服務。

必要條件

若要完成這個逐步解說,您必須要有:

  • Visual Studio 2008 或 Microsoft Visual Web Developer Express 版。

  • 在本機電腦上安裝 Microsoft Internet Information Services (IIS)。

建立具備 AJAX 能力的 Web 服務

本節說明如何建立具備 AJAX 能力的 Web 服務。

注意事項:

在這個逐步解說中必須使用 IIS 網站。

若要建立具備 AJAX 能力的 Web 服務

  1. 開啟 Visual Studio 2008 或 Microsoft Visual Web Developer Express 版。

  2. 按一下 [檔案] 功能表上的 [新網站]。

    [新網站] 對話方塊隨即出現。

  3. 按一下 [Visual Studio 安裝的範本] 之下的 [ASP.NET 網站]。

  4. 按一下 [瀏覽]。

  5. 按一下 [本機 IIS]。

  6. 按一下 [預設的網站]。

  7. 按一下右上角的 [建立新 Web 應用程式] 圖示。

    Visual Studio 會建立新的 IIS Web 應用程式。

  8. 指定名稱 HelloWorldService。

    注意事項:

    您所建立的網站名稱並不重要。

  9. 按一下 [開啟]。

    [新網站] 對話方塊隨即顯示,且最右邊的 [位置] 清單中會顯示新網站的名稱。位置包括通訊協定 (http://) 和位置 (localhost),這表示您正在使用本機 IIS 網站。

  10. 在 [語言] 清單中,按一下您想要操作的程式語言。

  11. 按一下 [確定]。

撰寫自訂 Web 服務

本節描述如何撰寫具備 AJAX 能力的 Web 服務,此服務會提供方法以傳回字串 "Hello World" 和目前的伺服器時間。

若要撰寫自訂 Web 服務

  1. 在 [方案總管] 中,以滑鼠右鍵按一下網站名稱 (https://localhost/HelloWorldService),然後按一下 [加入新項目]。

  2. 按一下 [Visual Studio 安裝的範本] 之下的 [Web 服務],然後在 [名稱] 方塊中輸入 HelloWorld.asmx。

  3. 確認已選取 [將程式碼置於個別檔案中] 核取方塊,然後按一下 [加入]。

    Visual Studio 2008 會建立由兩個檔案所組成的新 Web 服務。HelloWorld.asmx 檔案就是可被叫用 (Invoke) 以呼叫 Web 服務方法的檔案,這個方法會指向 Web 服務程式碼。程式碼本身位在 App_Code 資料夾內的類別檔案中 (HelloWorld.vb 或HelloWorld.cs,視程式設計語言而定)。程式碼檔包含 Web 服務的範本。

  4. 刪除類別中的現有程式碼,然後取代成下列程式碼:

    Imports System
    Imports System.Web
    Imports System.Collections
    Imports System.Web.Services
    Imports System.Web.Services.Protocols
    
    Namespace Samples.Aspnet
        <WebService([Namespace]:="http://mycompany.org/"), _
        WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1), _
        System.Web.Script.Services.ScriptService()> _
        Public Class HelloWorld
            Inherits System.Web.Services.WebService
    
            Public Sub New()
    
            End Sub 'New
    
    
            'Uncomment the following line if using designed components 
            'InitializeComponent(); 
    
            <WebMethod()> _
            Public Function Greetings() As String
                Dim serverTime As String = _
                    String.Format("Current date and time: {0}.", DateTime.Now)
                Dim greet As String = "Hello World. <br/>" + serverTime
                Return greet
    
            End Function 'Greetings
        End Class 'HelloWorld
    
    End Namespace
    
    using System;
    using System.Web;
    using System.Collections;
    using System.Web.Services;
    using System.Web.Services.Protocols;
    
    namespace Samples.Aspnet
    {
        [WebService(Namespace="http://mycompany.org")]
        [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
        // The following attribute allows the service to 
        // be called from script using ASP.NET AJAX.
        [System.Web.Script.Services.ScriptService]
        public class HelloWorld : System.Web.Services.WebService
        {
    
            public HelloWorld()
            {
    
                //Uncomment the following line if using designed components 
                //InitializeComponent(); 
            }
    
            [WebMethod]
            public string Greetings()
            {
                string serverTime =
                    String.Format("Current date and time: {0}.", DateTime.Now);
                string greetings = "Hello World! <br/>" + serverTime;
                return greetings;
            }
    
        }
    }
    

    請注意,函式名稱前面會有 WebMethodAttribute 屬性,做為函式宣告的一部分。此外,HelloWorld 類別必須以 ScriptServiceAttribute 屬性限定。

    這些屬性可讓具備 AJAX 能力的 ASP.NET 網頁中的指令碼呼叫 Web 服務。

  5. 儲存並關閉檔案。

  6. 開啟 HelloWorld.asmx 檔案,然後加入下列指示詞:

    <%@ WebService Language="VB" CodeBehind="~/App_Code/HelloWorld.vb" Class="Samples.Aspnet.HelloWorld" %>
    
    <%@ WebService Language="C#" CodeBehind="~/App_Code/HelloWorld.cs" Class="Samples.Aspnet.HelloWorld" %>
    
  7. 儲存並關閉檔案。

現在,您可以在瀏覽器中測試 Web 服務。這項測試並不使用指令碼來呼叫 Web 服務方法。這只是為了確認 Web 服務可以正確的運作。

若要測試 Web 服務

  1. 開啟瀏覽器並輸入下列 URL:https://localhost/HelloWorldService/HelloWorld.asmx。

    如此便會叫用 Web 服務,且瀏覽器中會出現一個顯示 Web 服務所公開 (Expose) 之方法的網頁。

  2. 按一下 [問候語]。出現一個頁面,顯示 [叫用] 按鈕。

  3. 按一下 [叫用] 按鈕以呼叫方法,並查看以 XML 格式傳回的值。

  4. 關閉瀏覽器。

您已完成了建立具備 AJAX 能力的 Web 服務。

使用 Web 服務

下一個步驟就是從用戶端指令碼呼叫 Web 服務。

若要從用戶端指令碼呼叫 Web 服務

  1. 在 [方案總管] 中,以滑鼠右鍵按一下網站名稱 (https://localhost/HelloWorldService),然後按一下 [加入新項目]。

  2. 按一下 [Visual Studio 安裝的範本] 之下的 [JScript 檔案],然後在 [名稱] 方塊中輸入 HelloWorld.js。

  3. 按一下 [確定]。

  4. 將下列程式碼加入至指令碼檔案:

    var helloWorldProxy;
    
    // Initializes global and proxy default variables.
    function pageLoad()
    {
        // Instantiate the service proxy.
        helloWorldProxy = new Samples.Aspnet.HelloWorld();
    
        // Set the default call back functions.
        helloWorldProxy.set_defaultSucceededCallback(SucceededCallback);
        helloWorldProxy.set_defaultFailedCallback(FailedCallback);
    }
    
    
    // Processes the button click and calls
    // the service Greetings method.  
    function OnClickGreetings()
    {
        var greetings = helloWorldProxy.Greetings();
    }
    
    // Callback function that
    // processes the service return value.
    function SucceededCallback(result)
    {
        var RsltElem = document.getElementById("Results");
        RsltElem.innerHTML = result;
    }
    
    // Callback function invoked when a call to 
    // the  service methods fails.
    function FailedCallback(error, userContext, methodName) 
    {
        if(error !== null) 
        {
            var RsltElem = document.getElementById("Results");
    
            RsltElem.innerHTML = "An error occurred: " + 
                error.get_message();
        }
    }
    
    if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();
    

    Default.aspx 頁面會使用這個用戶端指令碼來呼叫 HelloWorld 服務方法。

  5. 在 Visual Studio 2008 中,開啟 Default.aspx 網頁。

  6. 刪除頁面中現有的標記,然後取代成下列程式碼:

    <%@ Page Language="VB" AutoEventWireup="false" %>
    
    <!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 id="Head1" >
            <style type="text/css">
                body {  font: 11pt Trebuchet MS;
                        color: #000000;
                        padding-top: 72px;
                        text-align: center }
    
                .text { font: 8pt Trebuchet MS }
            </style>
    
            <title>Using AJAX Enabled ASP.NET Service</title>
    
        </head>
    
        <body>
            <form id="Form1" >
                <asp:ScriptManager  ID="scriptManager">
                    <Services>
                        <asp:ServiceReference path="~/HelloWorld.asmx" />
                    </Services>
                    <Scripts>
                        <asp:ScriptReference Path="~/HelloWorld.js" />
                    </Scripts>
                </asp:ScriptManager>
                <div>
                    <h3>Using AJAX Enabled ASP.NET Service</h3>
    
                    <table>
                        <tr align="left">
                            <td>Click to call the Hello World service:</td>
                            <td>
                                <button id="Button1" 
                                    onclick="OnClickGreetings(); return false;">Greetings</button>
                            </td>
                        </tr>
                    </table>
                </div>
            </form>
    
            <hr/>
    
            <div>
                <span id="Results"></span>
            </div>   
    
        </body>
    
    </html>
    
    <%@ Page Language="C#" %>
    
    <!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 id="Head1" >
            <style type="text/css">
                body {  font: 11pt Trebuchet MS;
                        color: #000000;
                        padding-top: 72px;
                        text-align: center }
    
                .text { font: 8pt Trebuchet MS }
            </style>
    
            <title>Using AJAX Enabled ASP.NET Service</title>
    
        </head>
    
        <body>
            <form id="Form1" >
                <asp:ScriptManager  ID="scriptManager">
                    <Services>
                        <asp:ServiceReference path="~/HelloWorld.asmx" />
                    </Services>
                    <Scripts>
                        <asp:ScriptReference Path="~/HelloWorld.js" />
                    </Scripts>
                </asp:ScriptManager>
                <div>
                    <h3>Using AJAX Enabled ASP.NET Service</h3>
    
                    <table>
                        <tr align="left">
                            <td>Click to call the Hello World service:</td>
                            <td>
                                <button id="Button1" 
                                    onclick="OnClickGreetings(); return false;">Greetings</button>
                            </td>
                        </tr>
                    </table>
                </div>
            </form>
    
            <hr/>
    
            <div>
                <span id="Results"></span>
            </div>   
    
        </body>
    
    </html>
    

    頁面內含 ScriptManager 控制項。Services 區段的 ServiceReference 項目中的 path 屬性會參考您先前建置的 HelloWorld 服務。Script 區段的 ServiceReference 項目中的 path 屬性會參考 HelloWorld.js 指令碼。

  7. 開啟瀏覽器並輸入下列 URL:

    http://<localhost>/HelloWorldService/Default.aspx

  8. 在顯示的頁面中,按一下 [問候語] 按鈕。

    這麼做會產生對 Web 服務的呼叫,此服務會傳回一個問候訊息和目前的伺服器日期和時間。

後續步驟

本逐步解說描述建立 Web 服務並從用戶端指令碼在網頁中呼叫此服務的基本原則,如果您想試驗其他更複雜的 Web 服務功能,建議您進一步探索下列各項:

請參閱

概念

將 Web 服務公開給用戶端指令碼

從用戶端指令碼呼叫 Web 服務

在 ASP.NET AJAX 中使用 Web 服務