架構優勢
- .ashx (IHttpHandler):輕量、無頁面生命週期、適合 API、檔案上傳、驗證碼、動態圖片。
- HTML 原生表單:無 ViewState、無 Control Tree、回應速度快、易於前端框架整合。
- AJAX (fetch/jQuery):無刷新體驗、JSON 交換、統一錯誤處理。
範例 1:同步表單提交 (傳統 Post-Redirect-Get)
Form.html (靜態頁面即可)
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>登入</title></head><body>
<form action="Login.ashx" method="post">
<label>帳號:<input name="username" required /></label><br/>
<label>密碼:<input name="password" type="password" required /></label><br/>
<button type="submit">登入</button>
</form>
</body></html>
Login.ashx.cs
using System.Web;
public class Login : IHttpHandler
{
public bool IsReusable => false;
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/html; charset=utf-8";
string user = context.Request.Form["username"];
string pwd = context.Request.Form["password"];
// 簡易驗證 (實務查 DB/Identity)
if (user == "admin" && pwd == "1234")
{
// 設定 FormsAuth Cookie
var ticket = new FormsAuthenticationTicket(1, user, DateTime.Now, DateTime.Now.AddHours(2), false, "");
string enc = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, enc) { HttpOnly = true, Secure = true };
context.Response.Cookies.Add(cookie);
// PRG 導向首頁
context.Response.Redirect("~/Default.aspx");
}
else
{
context.Response.Write("");
}
}
}
範例 2:AJAX 提交 (jQuery / fetch)
AjaxForm.html
<form id="ajaxForm">
<input name="email" type="email" placeholder="Email" required />
<input name="message" placeholder="意見" required />
<button type="submit">送出</button>
<div id="result"></div>
</form>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.7/dist/jquery.min.js"></script>
<script>
$('#ajaxForm').on('submit', function(e){
e.preventDefault();
$.ajax({
url: 'Feedback.ashx',
method: 'POST',
data: $(this).serialize(),
dataType: 'json',
success: function(res){
$('#result').html('' + res.msg + '
');
if(res.success) this.reset();
},
error: function(){ $('#result').html('網路錯誤
'); }
});
});
</script>
Feedback.ashx.cs
public class Feedback : IHttpHandler
{
public bool IsReusable => false;
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json; charset=utf-8";
try
{
string email = context.Request.Form["email"];
string msg = context.Request.Form["message"];
// 驗證
if (string.IsNullOrWhiteSpace(email) || !email.Contains("@"))
throw new ArgumentException("Email 格式錯誤");
// 寫入 DB / 發送郵件 (略)
// ...
context.Response.Write("{\"success\":true,\"msg\":\"感謝您的回饋!\"}");
}
catch (Exception ex)
{
context.Response.StatusCode = 400;
context.Response.Write($"{{\"success\":false,\"msg\":\"{HttpUtility.JavaScriptStringEncode(ex.Message)}\"}}");
}
}
}
範例 3:檔案上傳至 .ashx (支援進度條)
<form id="upForm" enctype="multipart/form-data">
<input type="file" name="file" id="fileInput" required />
<button type="submit">上傳</button>
<progress id="prog" value="0" max="100"></progress>
</form>
<script>
document.getElementById('upForm').addEventListener('submit', async (e) => {
e.preventDefault();
var fd = new FormData();
fd.append('file', document.getElementById('fileInput').files[0]);
await fetch('Upload.ashx', {
method: 'POST', body: fd,
// XMLHttpRequest 才能監聽進度
});
// 進度條需用 XMLHttpRequest 或 axios
});
</script>
部署與設定要點
- Web.config 註冊 (IIS 7+ 整合模式通常自動偵測,舊版需手動):
<system.webServer>
<handlers>
<add name="ASHX" path="*.ashx" verb="*" type="System.Web.UI.SimpleHandlerFactory" preCondition="integratedMode" />
</handlers>
</system.webServer>
- Session 存取:在 `.ashx` 實作 `IRequiresSessionState` (讀寫) 或 `IReadOnlySessionState` (唯讀)。
public class MyHandler : IHttpHandler, IRequiresSessionState { ... }
- 最大上傳大小:同 ASPX 設定 `httpRuntime maxRequestLength` / `requestLimits maxAllowedContentLength`。
安全性檢查清單
- ✅ 驗證 `Content-Type` 與檔案簽名 (Magic Number)。
- ✅ 產生隨機檔名儲存於 `App_Data` 或雲端儲存,禁止直接執行上傳目錄腳本。
- ✅ CSRF 保護:AJAX 請求攜帶 Anti-Forgery Token (Header `RequestVerificationToken`)。
- ✅ 輸出 JSON 時設定 `Content-Type: application/json` 並確保 UTF-8 編碼。