共用方式為


實作驗證的用戶端回呼範例

更新:2007 年 11 月

在用戶端回呼 (Callback) 中,用戶端指令碼函式會傳送要求給 ASP.NET Web 網頁,而這個網頁會接著執行其正常性生命週期的小型版本來處理回呼。為確認回呼事件是來自預期的使用者介面 (UI),您可以驗證回呼。回呼驗證需要在 Web 網頁呈現時註冊用於驗證的事件,然後在回呼時驗證該事件。

注意事項:

事件驗證可以協助保護 Web 應用程式安全,以預防偽造的回呼,但無法防止重新執行的攻擊。更完善的事件驗證機制應該考慮到 Web 應用程式的細節,以及使用者對其資源的存取權限。如需詳細資訊,請參閱 ASP.NET Web 應用程式安全性

本文所討論的範例是用戶端回呼實作 (C#) 範例用戶端回呼實作 (Visual Basic) 範例的擴充。在這些範例中,名為 ListBox1 的 ListBox 控制項是可顯示產品清單的伺服器端控制項,而 HTML <button> 項目 (不是 Button 伺服器控制項) 則會執行回呼以取得產品庫存資訊。範例的擴充部分是引入關於產品是否有特價的額外資訊,而且只有已通過驗證的使用者才可以檢視這項資訊。LoginView 控制項是和設為顯示額外內容的 LoggedInTemplate 屬性一起使用。Web 網頁的匿名使用者可以執行回呼以取得產品庫存資訊,反之已登入的使用者也可以執行回呼以取得特價資訊。只要使用者通過驗證,特價資訊的回呼就會被用來註冊事件驗證。這麼做能夠防止未經驗證的使用者執行回呼。

範例

說明

在下列範例中,Web 網頁會模擬資料庫查閱來判斷現有的商品數量,以及商品是否有特價。為了簡化範例,資料存放區是用兩個字典清單來表示。在實際執行應用程式中就會使用資料庫。本範例所示範的案例是驗證用戶端回呼會防止匿名使用者執行專為已通過驗證之使用者設計的回呼。

錯誤碼

<%@ Page Language="VB" AutoEventWireup="false" 
  CodeFile="ClientCallback.aspx.vb" Inherits="ClientCallback" %>

<!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" >
    <title>ASP.NET Example</title>
<script type="text/javascript">    
    function ReceiveServerData(rValue)
    {
        Results.innerText = rValue;
    }
  </script>
</head>
<body>
  <form id="form1" >
    <div>
      <asp:ListBox id="ListBox1" ></asp:ListBox>
      <br />
      <br />
      <button id="LookUpStockButton" onclick="LookUpStock()">Look Up Stock</button>
      <asp:LoginView id="LoginView1" >
      <LoggedInTemplate>
         <button id="LookUpSaleButton" onclick="LookUpSale()">Look Up Back Order</button>
      </LoggedInTemplate>
      </asp:LoginView>
      <br />
      Item status: <span id="Results"></span>
    </div>
  </form>
</body>
</html>
<%@ Page Language="C#" AutoEventWireup="true" 
  CodeFile="ClientCallback.aspx.cs" Inherits="ClientCallback" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 
  1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" >
    <title>ASP.NET Example</title>
<script type="text/javascript">    
    function ReceiveServerData(rValue)
    {
        Results.innerText = rValue;
    }
  </script>
</head>
<body>
  <form id="form1" >
    <div>
      <asp:ListBox id="ListBox1" ></asp:ListBox>
      <br />
      <br />
      <button id="LookUpStockButton" onclick="LookUpStock()">Look Up Stock</button>
      <asp:LoginView id="LoginView1" >
      <LoggedInTemplate>
         <button id="LookUpSaleButton" onclick="LookUpSale()">Look Up Back Order</button>
      </LoggedInTemplate>
      </asp:LoginView>
      <br />
      Item status: <span id="Results"></span>
    </div>
  </form>
</body>
</html>
Partial Class ClientCallback
    Inherits System.Web.UI.Page
    Implements System.Web.UI.ICallbackEventHandler

    Protected catalog As ListDictionary
    Protected saleitem As ListDictionary
    Protected returnValue As String
    Protected validationLookUpStock As String = "LookUpStock"
    Protected validationLookUpSale As String = "LookUpSale"
    Sub Page_Load(ByVal sender As Object, ByVal e As _
        System.EventArgs) Handles Me.Load

        Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), _
            validationLookUpStock, "function LookUpStock() {  " & _
            "var lb = document.forms[0].ListBox1; " & _
            "var product = lb.options[lb.selectedIndex].text;  " & _
            "CallServer(product, ""LookUpStock"");}  ", True)
        If (User.Identity.IsAuthenticated) Then
            Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), _
            validationLookUpSale, "function LookUpSale() {  " & _
            "var lb = document.forms[0].ListBox1; " & _
            "var product = lb.options[lb.selectedIndex].text;  " & _
            "CallServer(product, ""LookUpSale"");} ", True)
        End If

        Dim cbReference As String
        cbReference = "var param = arg + '|' + context;" & _
             Page.ClientScript.GetCallbackEventReference(Me, _
            "param", "ReceiveServerData", "context")
        Dim callbackScript As String = ""
        callbackScript &= "function CallServer(arg, context) { " & _
            cbReference & "} ;"
        Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), _
            "CallServer", callbackScript, True)

        ' Populate List Dictionary with invented database data
        catalog = New ListDictionary()
        saleitem = New ListDictionary()
        catalog.Add("monitor", 12)
        catalog.Add("laptop", 10)
        catalog.Add("keyboard", 23)
        catalog.Add("mouse", 17)
        saleitem.Add("monitor", 1)
        saleitem.Add("laptop", 0)
        saleitem.Add("keyboard", 0)
        saleitem.Add("mouse", 1)

        ListBox1.DataSource = catalog
        ListBox1.DataTextField = "key"
        ListBox1.DataBind()
    End Sub

    Public Sub RaiseCallbackEvent(ByVal eventArgument As String) _
    Implements System.Web.UI.ICallbackEventHandler.RaiseCallbackEvent

        Dim argParts() As String = eventArgument.Split("|"c)
        If ((argParts Is Nothing) OrElse (argParts.Length <> 2)) Then
            returnValue = "A problem occurred trying to retrieve stock count."
            Return
        End If

        Dim product As String = argParts(0)
        Dim validationaction = argParts(1)
        Select Case validationaction
            Case "LookUpStock"
                Try
                    Page.ClientScript.ValidateEvent("LookUpStockButton", validationaction)
                    If (catalog(product) Is Nothing) Then
                        returnValue = "Item not found."
                    Else
                        returnValue = catalog(product).ToString() & " in stock."
                    End If
                Catch
                    returnValue = "Can not retrieve stock count."
                End Try
            Case "LookUpSale"
                Try
                    Page.ClientScript.ValidateEvent("LookUpSaleButton", validationaction)
                    If (saleitem(product) Is Nothing) Then
                        returnValue = "Item not found."
                    Else
                        If (Convert.ToBoolean(saleitem(product))) Then
                            returnValue = "Item is on sale."
                        Else
                            returnValue = "Item is not on sale."
                        End If
                    End If
                Catch
                    returnValue = "Can not retrieve sale status."
                End Try

        End Select

    End Sub

    Public Function GetCallbackResult() _
    As String Implements _
    System.Web.UI.ICallbackEventHandler.GetCallbackResult

        Return returnValue

    End Function

    Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
        Page.ClientScript.RegisterForEventValidation("LookUpStockButton", _
          validationLookUpStock)
        If (User.Identity.IsAuthenticated) Then
            Page.ClientScript.RegisterForEventValidation("LookUpSaleButton", _
             validationLookUpSale)
        End If
        MyBase.Render(writer)
    End Sub
End Class
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class ClientCallback : System.Web.UI.Page,
     System.Web.UI.ICallbackEventHandler
{
    protected System.Collections.Specialized.ListDictionary catalog;
    protected System.Collections.Specialized.ListDictionary saleitem;
    protected String returnValue;
    protected String validationLookUpStock = "LookUpStock";
    protected String validationLookUpSale = "LookUpSale";
    protected void Page_Load(object sender, EventArgs e)
    {
        Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
            validationLookUpStock, "function LookUpStock() {  " +
            "var lb = document.forms[0].ListBox1; " +
            "var product = lb.options[lb.selectedIndex].text;  " +
            @"CallServer(product, ""LookUpStock"");}  ", true);
        if (User.Identity.IsAuthenticated)
        {
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
            validationLookUpSale, "function LookUpSale() {  " +
            "var lb = document.forms[0].ListBox1; " +
            "var product = lb.options[lb.selectedIndex].text;  " +
            @"CallServer(product, ""LookUpSale"");} ", true);
        }

        String cbReference = "var param = arg + '|' + context;" + 
            Page.ClientScript.GetCallbackEventReference(this,
            "param", "ReceiveServerData", "context");
        String callbackScript;
        callbackScript = "function CallServer(arg, context)" +
            "{ " + cbReference + "} ;";
        Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
            "CallServer", callbackScript, true);

        catalog = new System.Collections.Specialized.ListDictionary();
        saleitem = new System.Collections.Specialized.ListDictionary();
        catalog.Add("monitor", 12);
        catalog.Add("laptop", 10);
        catalog.Add("keyboard", 23);
        catalog.Add("mouse", 17);
        saleitem.Add("monitor", 1);
        saleitem.Add("laptop", 0);
        saleitem.Add("keyboard", 0);
        saleitem.Add("mouse", 1);

        ListBox1.DataSource = catalog;
        ListBox1.DataTextField = "key";
        ListBox1.DataBind();
    }
    public void RaiseCallbackEvent(String eventArgument)
    {
        string[] argParts = eventArgument.Split('|');
        if ((argParts == null) || (argParts.Length != 2))
        {
            returnValue = "A problem occurred trying to retrieve stock count.";
            return;
        }
        string product = argParts[0];
        string validationaction = argParts[1];
        switch (validationaction)
        {
            case "LookUpStock":
                try
                {
                    Page.ClientScript.ValidateEvent("LookUpStockButton", validationaction);
                    if (catalog[product] == null)
                    {
                        returnValue = "Item not found.";
                    }
                    else
                    {
                        returnValue = catalog[product].ToString() + " in stock.";
                    }
                }
                catch
                {
                    returnValue = "Can not retrieve stock count.";
                } 
                break;
            case "LookUpSale":
                try
                {
                    Page.ClientScript.ValidateEvent("LookUpSaleButton", validationaction);
                    if (saleitem[product] == null)
                    {
                        returnValue = "Item not found.";
                    }
                    else
                    {
                        if (Convert.ToBoolean(saleitem[product]))
                            returnValue = "Item is on sale.";
                        else
                            returnValue = "Item is not on sale.";
                    }
                }
                catch
                {
                    returnValue = "Can not retrieve sale status.";
                }
                break;
        }

    }
    public String GetCallbackResult()
    {
        return returnValue;
    }
    protected override void Render(HtmlTextWriter writer)
    {
        Page.ClientScript.RegisterForEventValidation("LookUpStockButton",
            validationLookUpStock);
        if (User.Identity.IsAuthenticated)
        {
            Page.ClientScript.RegisterForEventValidation("LookUpSaleButton",
                validationLookUpSale);
        }
        base.Render(writer);
    }
}

註解

網頁模擬資料庫查閱以判斷可用或在庫存中的產品系列項目數量 (螢幕、鍵盤等)。為了簡化這個程式碼範例,資料庫是用包含小型項目組合的字典清單來表示。針對資料表中的每個項目,索引鍵是項目名稱 (例如螢幕) 並且值是在庫存中的項目數量。在實際執行應用程式中就會使用資料庫。

當執行網頁時,ListBox 控制項會繫結至雜湊資料表,讓 ListBox 控制項顯示產品清單。對於已通過驗證的使用者,會以兩個 HTML <button> 項目 (其 onclick 事件分別繫結至名為 LookUpStock 的用戶端函式以及名為 LookUpSale 的用戶端函式) 來呈現網頁。對於匿名使用者,只會以一個 HTML <button> 項目 (其 onclick 事件繫結至 LookUpStock) 來呈現網頁。LoginView 控制項是用來指定要顯示哪一個按鈕。在網頁之覆寫的 Render 事件中,按鈕會被用來註冊驗證。如果使用者未通過驗證,就不會註冊可啟始 LookUpSale 之回呼的按鈕,而如果嘗試執行回呼的話,則會失敗。

程式碼後置 (Code-Behind) 的網頁會透過 RegisterClientScriptBlock 方法將用戶端指令碼加入網頁。加入網頁的指令碼包括了名為 CallServer 的函式,而這個函式會從 GetCallbackEventReference 方法中取得回傳至伺服器的方法名稱。

用戶端回呼會叫用 (Invoke) RaiseCallbackEvent 方法,以判斷傳遞給這個回呼的產品之現有庫存。GetCallbackResult 方法會傳回此值。請注意在用戶端指令碼和伺服端程式碼之間傳送的引數只能是字串。若要傳入或接收多個值,您可以分別在輸入或傳回字串中串連這些值。

安全性注意事項:

如果 Web 網頁和用戶端回呼處理的是機密資料的顯示,或是插入、更新或刪除資料的操作,建議您驗證回呼,以確保預期的使用者介面項目正在執行回呼。

請參閱

工作

HOW TO:在 ASP.NET Web 網頁中實作回呼

概念

在 ASP.NET 網頁中以程式設計方式實作用戶端回呼但不回傳

用戶端回呼實作 (C#) 範例

用戶端回呼實作 (Visual Basic) 範例

參考

ClientScriptManager

RegisterForEventValidation

ValidateEvent