在 ASP.NET WebForms 時代,Ajax.dll(Ajax.NET Professional)是實現客戶端直接調用服務端靜態方法的經典方案。本文記錄完整流程:從引用 DLL、編寫服務端標記方法、前端 JS 調用並解析返回字符串、賦值到表單控件,到 Web.config 註冊 HttpHandler。
public class AjaxMethod
{
public AjaxMethod() { }
[Ajax.AjaxMethod(Ajax.HttpSessionStateRequirement.Read)]
public static string GetCardMoney(string cardNo, string cardPwd)
{
string mConn = IConfiguration.getParameter("connectString");
IDBOSQL.IDBO dbo = IDBOSQL.IDBO.getIDBO(mConn);
dbo.openDatabase();
DataSet ds = dbo.executeSelectSql(
"select Card_Money,Service_Discount,Good_Discount " +
"from Table_CardInfo join Dic_CardType on Table_CardInfo.CardType_ID= Dic_CardType.CardType_ID " +
"where Card_NO='" + cardNo + "' and Card_Pwd= '" + cardPwd + "' and card_Status='正常'");
DataTable dt = ds.Tables[0];
string money = dt.Rows[0][0].ToString();
string service_discount = dt.Rows[0][1].ToString();
string good_discount = dt.Rows[0][2].ToString();
dbo.closeDatabase();
// 返回逗號分隔字符串,前端 split 解析
return money + "," + service_discount + "," + good_discount;
}
}
// 同步調用(Ajax.dll 默認同步模式)
var moneydiscount = AjaxMethod.GetCardMoney(card, pwd).value;
// 返回 "100,0.9,0.95" 格式字符串
var arr = moneydiscount.split(","); // 轉數組
// arr[0] = 餘額, arr[1] = 服務折扣, arr[2] = 商品折扣
document.getElementById("txtCard_Money1").value = arr[0];
document.getElementById("txtService_Discount").value = arr[1];
document.getElementById("txtGood_Discount").value = arr[2];
<httpHandlers>
<add verb="POST,GET" path="ajax/*.ashx" type="Ajax.PageHandlerFactory, Ajax" />
</httpHandlers>
cardNo/cardPwd 進 SQL 字符串,**生產環境嚴禁使用**,必須使用參數化查詢或 ORM。cardPwd 明文,需 HTTPS 強制加密,且不應在 URL/日誌中記錄。fetch/axios + 後端 Web API(非同步)。// 前端
fetch('/api/card/info', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ cardNo, cardPwd })
}).then(r => r.json()).then(data => {
document.getElementById('txtCard_Money1').value = data.money;
// ...
});
// 後端
[HttpPost]
public IActionResult GetCardInfo([FromBody] CardRequest req) {
// 參數化查詢,返回匿名對象或 DTO
return Ok(new { money, serviceDiscount, goodDiscount });
}
理解這段歷史代碼有助於維護老系統,但請務必在重構時修正上述安全與架構問題。