DIV CSS 佈局教程網

jQuery 以 Ajax 呼叫 ashx 一般 HTTP 處理常式完整範例
編輯:JQuery特效代碼     

在 ASP.NET 世界裡,.ashx 是「一般 HTTP 處理常式」(HttpHandler)的實作檔。它與 .aspx 最大的差別在於輕薄:不經過 Web Forms 的頁面生命週期、不解析控制項、沒有 ViewState,直接從 ProcessRequest 開始處理請求並輸出結果。

什麼時候該用 ashx

它最適合用來產生「不需要回發處理」的資料:動態圖片、動態文字、JSON 端點、檔案下載、簡單的 Ajax 後端。若你的需求只是「前端呼叫一支程式、拿一段資料回來」,ashx 比 aspx 更貼切,也省下可觀的執行緒與記憶體開銷。

後端:Login.ashx

public class Login : IHttpHandler {

    public void ProcessRequest(HttpContext context) {
        context.Response.ContentType = "application/json";

        // GET 方式取得傳遞的資料
        // string username = context.Request.QueryString["username"];
        // string password = context.Request.QueryString["password"];

        // POST 方式取得傳遞的資料
        string username = context.Request.Form["username"];
        string password = context.Request.Form["password"];
        string message = null;

        if (string.IsNullOrEmpty(username)) {
            message = "用戶名不能為空";
            context.Response.Write("{\"success\":false,\"message\":\"" + message + "\"}");
            context.Response.End();
        }

        if (string.IsNullOrEmpty(password)) {
            message = "密碼不能為空";
            context.Response.Write("{\"success\":false,\"message\":\"" + message + "\"}");
            context.Response.End();
        }

        if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password)) {
            if (username.ToUpper() == "ADMIN" && password == "123") {
                message = "登錄成功";
                context.Response.Write("{\"success\":true,\"message\":\"" + message + "\"}");
            } else {
                message = "用戶名或密碼錯誤";
                context.Response.Write("{\"success\":false,\"message\":\"" + message + "\"}");
            }
        }
        context.Response.End();
    }

    public bool IsReusable {
        get { return false; }
    }
}

註解裡那句「此 JSON 格式非常重要,否則會執行 jquery 的 error 函數」值得展開說明:jQuery 在 dataType: 'json' 下會嘗試解析回應文字,一旦解析失敗(例如多餘的 BOM、多了未轉義的換行、或根本回傳 HTML 錯誤頁),就會判定為請求失敗並跳到 error 回呼。手寫 JSON 字串時,只要 message 裡出現引號或換行就會出事。

更穩健的做法是用序列化器,讓框架負責轉義:

context.Response.ContentType = "application/json";
context.Response.Write(new JavaScriptSerializer().Serialize(new {
    success = false,
    message = message
}));

或使用 Json.NET 的 JsonConvert.SerializeObject()。

前端:HTML 頁面

<!DOCTYPE html>
<html>
<head>
<title>jQuery 訪問 ashx 文件</title>
<script src="Scripts/jquery-1.4.1.min.js"></script>
<script type="text/javascript">
function login() {
    $.ajax({
        url: 'common/handler/Login.ashx',
        type: 'POST',
        data: {
            'username': $("#txtUsername").val(),
            'password': $("#txtPassword").val()
        },
        dataType: 'json',
        timeout: 50000,
        success: function (response) {
            alert(response.message);
        },
        error: function (err) {
            alert("執行失敗");
        }
    });
}
</script>
</head>
<body>
<div style="width:400px; height:300px; margin:0 auto; background:#c0c0c0;">
  <dl style="width:270px;">
    <dd><span>用戶名:</span>
        <input type="text" style="width:150px;" id="txtUsername" /></dd>
    <dd><span>密 碼:</span>
        <input type="password" style="width:150px;" id="txtPassword" /></dd>
    <dd><input type="button" style="width:65px; height:23px; float:right;"
               onclick="login()" value="登錄" /></dd>
  </dl>
</div>
</body>
</html>

這個示範絕不能上 production

範例中的帳號密碼是硬編碼在原始碼裡的 ADMIN / 123。這在真實環境中是嚴重的安全缺失,任何能讀到程式碼或反編譯 DLL 的人都掌握了全部憑證。登入功能至少應做到:

  • 密碼以加鹽雜湊(bcrypt、PBKDF2、Argon2)儲存與比對,絕不明文存放。
  • 全部走 HTTPS,避免憑證在傳輸中曝光。
  • 加入失敗次數限制與鎖定機制,抵抗暴力破解。
  • 成功後建立 Session 或核發 token,並設定合理的中斷時間。
  • 回傳訊息不要區分「帳號不存在」與「密碼錯誤」,一律用「帳號或密碼錯誤」,以免成為帳號列舉的工具。

此外,前端只對 success 做 alert 而不導向,也示範了不足之處——實際登入成功後應導向後台首頁或更新頁面狀態。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved