首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

ASP.NET AJAX 登錄傳遞用戶名:Generic Handler 替代 WebForm 最佳實踐

     編輯:程式設計綜合問答

傳統 WebForm (`*.aspx`) 處理 AJAX 請求存在生命周期開銷大、ViewState 干擾、難以返回純 JSON 等問題。推薦使用 **Generic Handler (`*.ashx`)** 或 **Web API** 作為 AJAX 端點。

為什麼棄用 .aspx 做 AJAX?

  • 完整頁面生命周期(Init/Load/Render)開銷大。
  • 需手動 `Response.Clear()`、`Response.ContentType = "application/json"`。
  • ViewState 可能導致請求體膨脹、驗證失敗。

Generic Handler 實現登錄驗證

1. LoginHandler.ashx

<%@ WebHandler Language="C#" Class="LoginHandler" %>
using System.Web;
using System.Web.Script.Serialization;

public class LoginHandler : IHttpHandler {
    public void ProcessRequest(HttpContext context) {
        context.Response.ContentType = "application/json";
        var username = context.Request["username"];
        var password = context.Request["password"];
        
        // 業務驗證邏輯
        bool success = Membership.ValidateUser(username, password);
        var result = new { success, message = success ? "登錄成功" : "用戶名或密碼錯誤" };
        
        context.Response.Write(new JavaScriptSerializer().Serialize(result));
    }
    public bool IsReusable => false;
}

2. 前端 jQuery 調用

$('#btnLogin').click(function() {
    $.post('LoginHandler.ashx', {
        username: $('#txtUser').val(),
        password: $('#txtPwd').val()
    }, function(res) {
        if (res.success) {
            // 登錄成功:存儲用戶名並跳轉
            sessionStorage.setItem('username', $('#txtUser').val());
            location.href = 'Welcome.aspx';
        } else {
            alert(res.message);
        }
    }, 'json');
});

3. 目標頁面讀取顯示

// Welcome.aspx 頁面加載時
<script>
document.getElementById('welcome').textContent = 
    sessionStorage.getItem('username') + ',您好!';
</script>

進階:ASP.NET Web API (推薦新項目)

[RoutePrefix("api/auth")]
public class AuthController : ApiController {
    [HttpPost, Route("login")]
    public IHttpActionResult Login(LoginDto dto) {
        if (Membership.ValidateUser(dto.Username, dto.Password))
            return Ok(new { token = JwtHelper.Generate(dto.Username) });
        return BadRequest("Invalid credentials");
    }
}

Web API 原生支援屬性路由、模型綁定、內容協商、OAuth/JWT,是現代 ASP.NET 應用的標準選擇。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved