在 ASP.NET AJAX 中使用 Web 服務

更新:2007 年 11 月

本主題說明如何在具備 AJAX 技術的 ASP.NET Web 網頁中,存取用戶端指令碼的 Web 服務。這些服務可能是您建立的自訂服務,或是內建的應用程式服務。這些應用程式服務屬於 ASP.NET AJAX 內容的一部分,並且包含驗證、角色和設定檔服務。

自訂 Web 服務的可能形式有 .ASP.NET Web 服務 (.asmx 服務) 或 Windows Communication Foundation (WCF) 服務 (.svc 服務)。

本主題包含下列資訊:

  • 案例

  • 背景

  • 範例

  • 其他資源

  • 類別參考

  • 新功能

案例

您可以在下情況中使用 WCF 和 ASP.NET:

  • 如果您已經建立 WCF 服務,可以加入端點,讓具備 AJAX 技術之 Web 網頁中的指令碼可以存取這些服務。如需詳細資訊,請參閱將 WCF 服務公開給用戶端指令碼

  • 如果您已經建立 ASP.NET Web (.asmx) 服務,可以修改這些服務,讓採用 AJAX 技術之 Web 網頁中的指令碼可以存取相同的服務。如需詳細資訊,請參閱將 Web 服務公開給用戶端指令碼

  • 如果您想建立從 ASP.NET AJAX Web 網頁存取的自訂 Web 服務,可以將它實作為 WCF 服務或 ASP.NET Web 服務 (.asmx 檔)。

  • 您可以使用內建的 ASP.NET 應用程式服務,在採用 AJAX 技術之 Web 網頁中執行的用戶端指令碼,存取使用者的驗證、角色和設定檔等資訊。如需詳細資訊,請參閱搭配 ASP.NET AJAX 使用表單驗證

背景

ASP.NET 可以讓您建立可從 Web 網頁中用戶端指令碼存取的 Web 服務。這些網頁會透過使用 AJAX 技術進行 Web 服務呼叫的 Web 服務通訊層,與伺服器進行通訊。資料通常都是以 JSON 格式,以非同步的方式在用戶端和伺服器之間進行交換。

AJAX 用戶端的用戶端伺服器通訊

在採用 AJAX 技術的 Web 網頁中,瀏覽器會對伺服器提出網頁的初始要求,然後再對 Web 服務提出資料的後續非同步要求。用戶端通訊項目的形式為可從伺服器及核心用戶端指令碼程式庫下載的 Proxy 類別,而伺服器通訊項目則是處理常式和自訂服務。下圖顯示與用戶端和伺服器間通訊有關的項目。

用戶端伺服器通訊

AJAX 用戶端架構

瀏覽器使用 Proxy 類別呼叫 Web 服務方法。Proxy 類別是在載入網頁時由伺服器自動產生並且下載至瀏覽器的指令碼。Proxy 類別提供用戶端物件來代表 Web 服務的公開方法。

為了呼叫 Web 服務方法,用戶端指令碼會呼叫 Proxy 類別中對應的方法。這些呼叫是透過 XMLHTTP 物件,以非同步方式進行。

Web 服務通訊層包含可以讓 Proxy 類別進行服務呼叫的程式庫指令碼類型。如需詳細資訊,請參閱 Sys.Net 命名空間中所包含的類別。

Proxy 類別和核心 Web 服務通訊層中的程式碼隱藏了 XMLHTTP 的複雜度與瀏覽器之間的差異。這也簡化了呼叫 Web 服務時所需要的用戶端指令碼。

提出 Web 服務要求的方法共有兩種:

  • 使用 HTTP POST 動詞命令呼叫 Web 服務。POST 要求具有主體,而主體中則包含瀏覽器傳送至伺服器的資料。這種要求並無大小上限,因此當資料大小超過 GET 要求的內建 (Intrinsic) 大小上限時,您可以使用 POST 要求。用戶端會將要求序列化為 JSON 格式,再將它當做 POST 資料傳送到伺服器。伺服器會將 JSON 資料還原序列化為 .NET Framework 型別,並進行實際的 Web 服務呼叫。在回應期間,伺服器會序列化傳回值並將它們傳遞回用戶端,由用戶端將這些值還原序列化為 JavaScript 物件以供處理。

  • 使用 HTTP GET 動詞命令呼叫 Web 服務。這種方法與 POST 要求非常類似,但具有下列差異:

    • 用戶端使用查詢字串將參數傳送至伺服器。

    • GET 要求只能呼叫使用 ScriptMethodAttribute 屬性 (Attribute) 設定的 Web 服務方法。

    • 資料大小限制為瀏覽器所允許的 URL 長度。

      注意事項:

      用來修改伺服器之資料或公開重要資訊的方法呼叫都應該避免使用 GET 要求。在 GET 要求中,訊息是由瀏覽器編碼成 URL,因此較容易成為竄改的目標。不論是 GET 或 POST 要求,您都應該遵照安全性方針來保護機密資料。

下圖顯示 ASP.NET AJAX 用戶端架構。

AJAX 用戶端架構

用戶端架構的項目包括核心程式庫中的 Web 服務通訊層,以及網頁上使用之服務適用的已下載 Proxy 類別。圖中顯示的個別項目如下:

  • 自訂服務 Proxy 類別:這些項目包括伺服器自動產生並下載至瀏覽器的用戶端指令碼。Proxy 類別會為網頁中使用的每一項 WCF 或 ASMX 服務提供物件 (也就是說,它們會為網頁中 ScriptManager 控制項之 ServiceReferences 項目中的每個項目提供物件)。在用戶端指令碼中呼叫 Proxy 方法,可以建立對應於伺服器上之 Web 服務方法所提出的非同步要求。

  • 驗證 Proxy 類別:AuthenticationService Proxy 類別是由伺服器驗證應用程式服務所產生,可以讓使用者透過瀏覽器中的 JavaScript 登入或登出,而不需要來回存取伺服器。

  • 角色 Proxy 類別:RoleService Proxy 類別是由伺服器角色應用程式服務所產生,可以讓您透過 JavaScript 來將使用者設成群組,並將每個群組視為一個單位,而不需要來回存取伺服器。這對於啟用或拒絕存取伺服器資源可能非常有用。

  • 設定檔 Proxy 類別:ProfileService 類別是由伺服器設定檔應用程式服務所產生,可以讓用戶端透過 JavaScript 取得目前使用者的設定檔資訊,而不需要來回存取伺服器。

  • 頁面方法 Proxy 類別:此類別提供了指令碼基礎結構,供用戶端指令碼呼叫 ASP.NET 網頁中的靜態 (Static) 方法,就如同它們是 Web 服務方法一樣。如需詳細資訊,請參閱從用戶端指令碼呼叫 Web 服務

  • Web 服務通訊層:這是包含用戶端指令碼類型的程式庫。這些類型可以讓瀏覽器 (用戶端) 與伺服器上的服務進行通訊。它們也可以讓用戶端應用程式減少在用戶端和伺服器之間建立及維護非同步通訊時的複雜性。這些類別會封裝提供非同步功能的瀏覽器 XMLHTTP 物件,也可以讓用戶端應用程式與瀏覽器分開運作。以下是 Web 服務通訊層的主要項目:

    • WebRequest:此項目提供了用來提出 Web 要求的用戶端指令碼。如需詳細資訊,請參閱 WebRequest 類別。

    • WebRequestManager:此項目負責管理由 Sys.Net.WebRequest 物件發出之 Web 要求給相關執行程式物件的流程。如需詳細資訊,請參閱 WebRequestManager 類別。

    • XmlHttpExecutor:此項目可利用瀏覽器的 XMLHTTP 支援,提出非同步網路要求。如需詳細資訊,請參閱 XmlHttpExecutor 類別。

    • JSON 序列化:此項目可將 JavaScript 物件序列化為 JSON 格式。還原序列化 (Deserialization) 則可使用 JavaScript eval 函式來執行。如需詳細資訊,請參閱 JavaScriptSerializer 類別。

預設的序列化 (Serialization) 格式是 JSON,但是在 Web 服務和 ASP.NET Web 網頁中的個別方法可能會傳回諸如 XML 等的其他格式。方法的序列化格式可以使用屬性來指定。例如,針對 ASMX 服務,您可以設定 ScriptMethodAttribute 屬性,讓 Web 服務方法傳回 XML 資料,如下列範例所示:

[ScriptMethod(ResponseFormat.Xml)] 

<ScriptMethod(ResponseFormat.Xml)> 

AJAX 伺服器架構

下圖顯示 AJAX 伺服器架構,其中包括可用來和用戶端應用程式進行通訊的項目。

AJAX 伺服器架構

伺服器架構的項目包括具有 HTTP 處理常式及序列化類別的 Web 服務通訊層、自訂服務、頁面方法和應用程式服務。圖中顯示的個別項目如下:

  • 自訂 Web 服務:這些服務提供了您所實作的服務功能,並將適當的回應傳回給用戶端。自訂 Web 服務可能是 ASP.NET 或 WCF 服務。Web 服務通訊層會自動產生可從用戶端指令碼非同步呼叫的用戶端指令碼 Proxy 類別。

  • 頁面方法:這個元件可讓系統比照呼叫 Web 服務方法的方式來呼叫 ASP.NET 網頁中的方法。頁面方法必須定義在呼叫此頁面方法的頁面中。

  • 驗證服務:驗證服務會產生驗證 Proxy 類別,讓使用者可以透過用戶端 JavaScript 登入或登出。這個應用程式服務永遠都可使用,您不需要將具現化。如需詳細資訊,請參閱搭配 ASP.NET AJAX 使用表單驗證

  • 角色服務:角色服務會產生角色 Proxy 類別,讓用戶端 JavaScript 可以存取目前已驗證之使用者的角色資訊。這個應用程式服務永遠都可使用,您不需要將它具現化。如需詳細資訊,請參閱搭配 ASP.NET AJAX 使用角色資訊

  • 設定檔服務:設定檔服務會產生設定檔 Proxy 類別,讓用戶端 JavaScript 可以取得及設定與目前要求相關聯之使用者的設定檔屬性。這個應用程式服務永遠都可使用,您不需要將它具現化。如需詳細資訊,請參閱搭配 ASP.NET AJAX 使用設定檔資訊

  • JSON 序列化:伺服器 JSON 序列化元件可以針對一般的 .NET Framework 型別進行可自訂的 JSON 格式序列化及還原序列化作業。如需詳細資訊,請參閱 JavaScriptSerializer

  • XML 序列化:Web 服務通訊層支援可將 SOAP 要求轉換成 Web 服務,以及將 XML 型別從 JSON 要求還原成 Web 服務的 XML 序列化。

範例

下列範例示範如何從用戶端指令碼呼叫 ASP.NET 和 WCF 服務。如需有關如何從用戶端指令碼呼叫應用程式服務的範例,請參閱本文件的其他章節 (本主題稍後將提供相關的連結)。

在 AJAX 中呼叫 Web 服務方法

.NET Framework 可讓您使用用戶端指令,從瀏覽器非同步呼叫 ASP.NET Web 服務 (.asmx) 方法。這個頁面可以呼叫伺服器端方法,不需回傳也不需重新整理整個頁面,因為只有資料會在瀏覽器和伺服器之間傳輸。

下列範例示範如何在 ASP.NET Web 網頁中公開 Web 服務方法。

<%@ Page Language="VB" %>

<!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;
                    font-color: #000000;
                    padding-top: 72px;
                    text-align: center }

            .text { font: 8pt Trebuchet MS }
        </style>

        <title>Simple Web Service</title>

            <script type="text/javascript">

            // This function calls the Web Service method.  
            function GetServerTime()
            {
                Samples.AspNet.ServerTime.GetServerTime(OnSucceeded);
            }

            // This is the callback function that
            // processes the Web Service return value.
            function OnSucceeded(result)
            {
                var RsltElem = document.getElementById("Results");
                RsltElem.innerHTML = result;
            }

        </script>

    </head>

    <body>
        <form id="Form1" >
         <asp:ScriptManager  ID="scriptManager">
                <Services>
                    <asp:ServiceReference path="ServerTime.asmx" />
                </Services>
            </asp:ScriptManager>
            <div>
                <h2>Server Time</h2>
                    <p>Calling a service that returns the current server time.</p>

                    <input id="EchoButton" type="button" 
                        value="GetTime" onclick="GetServerTime()" />
            </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;
                    font-color: #000000;
                    padding-top: 72px;
                    text-align: center }

            .text { font: 8pt Trebuchet MS }
        </style>

        <title>Simple Web Service</title>

            <script type="text/javascript">

            // This function calls the Web Service method.  
            function GetServerTime()
            {
                Samples.AspNet.ServerTime.GetServerTime(OnSucceeded);
            }

            // This is the callback function that
            // processes the Web Service return value.
            function OnSucceeded(result)
            {
                var RsltElem = document.getElementById("Results");
                RsltElem.innerHTML = result;
            }

        </script>

    </head>

    <body>
        <form id="Form1" >
         <asp:ScriptManager  ID="scriptManager">
                <Services>
                    <asp:ServiceReference path="ServerTime.asmx" />
                </Services>
            </asp:ScriptManager>
            <div>
                <h2>Server Time</h2>
                    <p>Calling a service that returns the current server time.</p>

                    <input id="EchoButton" type="button" 
                        value="GetTime" onclick="GetServerTime()" />
            </div>
        </form>

        <hr/>

        <div>
            <span id="Results"></span>
        </div>   

    </body>

</html>

下列範例顯示頁面指令碼所呼叫的 Web 網頁和相關 Web 服務。

<%@ WebService Language="VB" Class="Samples.AspNet.ServerTime" %>

Imports System.Web
Imports System.Web.Services
Imports System.Xml
Imports System.Web.Services.Protocols
Imports System.Web.Script.Services

Namespace Samples.AspNet

    <WebService(Namespace:="http://tempuri.org/")> _
    <WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
    <ScriptService()> _
    Public Class ServerTime
        Inherits System.Web.Services.WebService

        <WebMethod()> _
        Public Function GetServerTime() As String
            Return String.Format("The current time is {0}.", _
                DateTime.Now)

        End Function
    End Class

End Namespace

<%@ WebService Language="C#" Class="Samples.AspNet.ServerTime" %>

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

namespace Samples.AspNet
{

    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ScriptService]
    public class ServerTime : System.Web.Services.WebService
    {

        [WebMethod]
        public string GetServerTime()
        {
            return String.Format("The server time is {0}.", 
                DateTime.Now);

        }

    }

}

從 AJAX 用戶端提出 HTTP 要求

上述範例示範如何透過呼叫 Web 服務自動產生的 Proxy 類別,從用戶端指令碼呼叫 Web 服務。您也可以從用戶端指令碼對 Web 服務進行較低階的呼叫。如果您必須管理通訊層或檢查在伺服器上來回傳送的資料,可能就會這樣做。若要使用這種方式呼叫 Web 服務,請使用 WebRequest 類別。

下列範例示範如何使用 WebRequest 物件來實作連接到指定之 URL (HTTP 端點) 的 GET 和 POST Web 要求。

// ConnectingEndPoints.js

var resultElement;

function pageLoad()
{
    resultElement = $get("ResultId");
}

// This function performs a GET Web request.
function GetWebRequest()
{
    alert("Performing Get Web request.");

    // Instantiate a WebRequest.
    var wRequest = new Sys.Net.WebRequest();

    // Set the request URL.      
    wRequest.set_url("getTarget.htm");
    alert("Target Url: getTarget.htm");

    // Set the request verb.
    wRequest.set_httpVerb("GET");

    // Set the request callback function.
    wRequest.add_completed(OnWebRequestCompleted);

    // Clear the results area.
    resultElement.innerHTML = "";

    // Execute the request.
    wRequest.invoke();  
}

// This function performs a POST Web request.
function PostWebRequest()
{
    alert("Performing Post Web request.");

    // Instantiate a WebRequest.
    var wRequest = new Sys.Net.WebRequest();

    // Set the request URL.      
    wRequest.set_url("postTarget.aspx");
    alert("Target Url: postTarget.aspx");

    // Set the request verb.
    wRequest.set_httpVerb("POST");

    // Set the request handler.
    wRequest.add_completed(OnWebRequestCompleted);

    // Set the body for he POST.
    var requestBody = 
        "Message=Hello! Do you hear me?";
    wRequest.set_body(requestBody);
    wRequest.get_headers()["Content-Length"] = 
        requestBody.length;

    // Clear the results area.
   resultElement.innerHTML = "";

    // Execute the request.
    wRequest.invoke();              
}


// This callback function processes the 
// request return values. It is called asynchronously 
// by the current executor.
function OnWebRequestCompleted(executor, eventArgs) 
{    
    if(executor.get_responseAvailable()) 
    {
        // Clear the previous results. 

       resultElement.innerHTML = "";

        // Display Web request status. 
       resultElement.innerHTML +=
          "Status: [" + executor.get_statusCode() + " " + 
                    executor.get_statusText() + "]" + "<br/>";

        // Display Web request headers.
       resultElement.innerHTML += 
            "Headers: ";

       resultElement.innerHTML += 
            executor.getAllResponseHeaders() + "<br/>";

        // Display Web request body.
       resultElement.innerHTML += 
            "Body:";

      if(document.all)
        resultElement.innerText += 
           executor.get_responseData();
      else
        resultElement.textContent += 
           executor.get_responseData();
    }

}
if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();

在 AJAX 中呼叫 WCF 服務作業

您可以從用戶端指令碼非同步地呼叫 Windows Communication Foundation (WCF) 服務 (.svc),呼叫的方式基本上和呼叫 .asmx 架構的服務一樣。下列範例示範如何在 ASP.NET Web 網頁中公開及呼叫 WCF 服務作業。

<%@ Page Language="VB" AutoEventWireup="true" %>

<!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 >
    <style type="text/css">
        body {  font: 11pt Trebuchet MS;
                font-color: #000000;
                padding-top: 72px;
                text-align: center }

        .text { font: 8pt Trebuchet MS }
    </style>
    <title>Simple WCF Service Page</title>

</head>
<body>
    <form id="form1" >
        <asp:ScriptManager ID="ScriptManager1" >
            <Services>
                <asp:ServiceReference 
                    Path="SimpleService.svc/ws"/>
            </Services>
            <Scripts>
                <asp:ScriptReference Path="service.js" />
            </Scripts>
        </asp:ScriptManager>
        
        <div>
            <h2>Simple WCF Service</h2>
            <input type='button' name="clickme"  value="Greetings" 
                onclick="javascript:OnClick()" /> &nbsp; &nbsp;
            <input type='button' name="clickme2"  value="Greetings2" 
                onclick="javascript:OnClick2()" />
            <hr/>
            <div>
                <span id="Results"></span>
            </div> 
        </div>

    </form>
</body>
</html>
<%@ Page Language="C#" AutoEventWireup="true"%>

<!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 >
    <style type="text/css">
        body {  font: 11pt Trebuchet MS;
                font-color: #000000;
                padding-top: 72px;
                text-align: center }

        .text { font: 8pt Trebuchet MS }
    </style>
    <title>Simple WCF Service Page</title>

</head>
<body>
    <form id="form1" >
        <asp:ScriptManager ID="ScriptManager1" >
            <Services>
                <asp:ServiceReference 
                    Path="SimpleService.svc/ws"/>
            </Services>
            <Scripts>
                <asp:ScriptReference Path="service.js" />
            </Scripts>
        </asp:ScriptManager>
        
        <div>
            <h2>Simple WCF Service</h2>
            <input type='button' name="clickme"  value="Greetings" 
                onclick="javascript:OnClick()" /> &nbsp; &nbsp;
            <input type='button' name="clickme2"  value="Greetings2" 
                onclick="javascript:OnClick2()" />
            <hr/>
            <div>
                <span id="Results"></span>
            </div> 
        </div>

    </form>
</body>
</html>
var ServiceProxy;

function pageLoad()
{
    ServiceProxy = new ISimpleService();
    ServiceProxy.set_defaultSucceededCallback(SucceededCallback);
}

function OnClick()
{
    // var myService = new ISimpleService();
    ServiceProxy.HelloWorld1("George");
}

function OnClick2()
{
    var dc = new DataContractType();
    dc.FirstName = "George";
    dc.LastName = "Washington";
    ServiceProxy.HelloWorld2(dc);      
}

// This is the callback function that
// processes the Web Service return value.
function SucceededCallback(result, userContext, methodName)
{
    var RsltElem = document.getElementById("Results");
    RsltElem.innerHTML = result + " from " + methodName + ".";
}
if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();
Imports System
Imports System.Web
Imports System.Collections
Imports System.Collections.Generic
Imports System.Threading
Imports System.Xml
Imports System.Xml.Serialization
Imports System.Text
Imports System.IO
Imports System.Runtime.Serialization
Imports System.ServiceModel
Imports System.ServiceModel.Description
Imports System.ServiceModel.Dispatcher
Imports System.ServiceModel.Channels
Imports System.ServiceModel.Activation


' This a WCF service which consists of a contract, 
' defined below as ISimpleService, and DataContractType, 
' a class which implements that interface, see SimpleService, 
' and configuration entries that specify behaviors associated with 
' that implementation (see <system.serviceModel> in web.config)
Namespace Aspnet.Samples.SimpleService

    <ServiceContract()> _
    Public Interface ISimpleService
        <OperationContract()> _
        Function HelloWorld1(ByVal value1 As String) As String
        <OperationContract()> _
        Function HelloWorld2(ByVal dataContractValue1 _
        As DataContractType) As String
    End Interface 'ISimpleService

    <ServiceBehavior(IncludeExceptionDetailInFaults:=True), _
    AspNetCompatibilityRequirements(RequirementsMode:= _
    AspNetCompatibilityRequirementsMode.Allowed)> _
    Public Class SimpleService
        Implements ISimpleService

        Public Sub New()

        End Sub 'New

        Public Function HelloWorld1(ByVal value1 As String) As String _
        Implements ISimpleService.HelloWorld1
            Return "Hello " + value1
        End Function 'HelloWorld1

        Public Function HelloWorld2(ByVal dataContractValue1 _
        As DataContractType) As String _
        Implements ISimpleService.HelloWorld2
            Return "Hello " + dataContractValue1.FirstName + " " + _
            dataContractValue1.LastName
        End Function 'HelloWorld2
    End Class 'SimpleService

    <DataContract()> _
    Public Class DataContractType
        Private _firstName As String
        Private _lastName As String


        <DataMember()> _
        Public Property FirstName() As String
            Get
                Return _firstName
            End Get
            Set(ByVal value As String)
                _firstName = value
            End Set
        End Property

        <DataMember()> _
        Public Property LastName() As String
            Get
                Return _lastName
            End Get
            Set(ByVal value As String)
                _lastName = value
            End Set
        End Property
    End Class 'DataContractType 
End Namespace

using System;
using System.Web;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Xml;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Channels;
using System.ServiceModel.Activation;

// This a WCF service which consists of a contract, 
// defined below as ISimpleService, and DataContractType, 
// a class which implements that interface, see SimpleService, 
// and configuration entries that specify behaviors associated with 
// that implementation (see <system.serviceModel> in web.config)

namespace Aspnet.Samples
{
    [ServiceContract()]
    public interface ISimpleService
    {
        [OperationContract]
        string HelloWorld1(string value1);
        [OperationContract]
        string HelloWorld2(DataContractType dataContractValue1);
    }

    [ServiceBehavior(IncludeExceptionDetailInFaults = true)]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class SimpleService : ISimpleService
    {
        public SimpleService()
        { }

        public string HelloWorld1(string value1)
        {
            return "Hello " + value1;
        }
        public string HelloWorld2(DataContractType dataContractValue1)
        {
            return "Hello " + dataContractValue1.FirstName +
                                " " + dataContractValue1.LastName;
        }
    }

    [DataContract]
    public class DataContractType
    {
        string firstName;
        string lastName;

        [DataMember]
        public string FirstName
        {
            get { return firstName; }
            set { firstName = value; }
        }
        [DataMember]
        public string LastName
        {
            get { return lastName; }
            set { lastName = value; }
        }
    }

}

其他範例

回到頁首

類別參考

下表列出與可從用戶端指令碼呼叫之 Web 服務相關聯的主要類別。

用戶端命名空間

名稱

說明

Sys.Net 命名空間

包含的類別可用來管理 ASP.NET AJAX 用戶端應用程式和伺服器端 Web 服務之間的通訊。Sys.Net 命名空間是 Microsoft AJAX Library 的一部分。

Sys.Serialization 命名空間

包含的類別與 ASP.NET AJAX 用戶端應用程式的資料序列化有關。

Sys.Services 命名空間

包含的型別可提供 ASP.NET AJAX 用戶端應用程式對 ASP.NET 驗證服務、設定檔服務和其他應用程式服務的設定檔存取權。Sys.Services 命名空間是 Microsoft AJAX Library 的一部分。

伺服器命名空間

名稱

說明

System.Web.Script.Serialization

包含的類別可提供 Managed 型別的「JavaScript 物件標記法」(JSON) 序列化和還原序列化。它也提供了自訂序列化行為的擴充性功能。

回到頁首

其他資源

關於原生 XMLHTTP

http://www.json.org

Windows Communication Foundation 是什麼?

XML Web Service 基礎結構

WCF 服務與 ASP.NET

了解服務導向架構

新功能

以下是 ASP.NET 3.0 版中的新功能:

  • Windows Communication Foundation (WCF) 中的應用程式服務。

  • AJAX 中從 .NET Framework 用戶端應用程式呼叫的應用程式服務。

回到頁首

請參閱

工作

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

概念

搭配 ASP.NET AJAX 使用表單驗證

ASP.NET 應用程式服務概觀