最輕量、無 ViewState、適合高頻 AJAX 請求。
<%@ WebHandler Language="C#" Class="JsonHandler" %>
using System; using System.Web; using System.Web.Script.Serialization; using System.Collections.Generic;
public class JsonHandler : IHttpHandler {
public void ProcessRequest(HttpContext context) {
context.Response.ContentType = "application/json"; // 標準 MIME
context.Response.Cache.SetNoStore(); // 禁用快取
string name = context.Request["name"];
var dict = new SortedDictionary<string, object> {
["message"] = string.IsNullOrEmpty(name) ? "無名氏" : $"你好 {name}, {DateTime.Now}"
};
context.Response.Write(new JavaScriptSerializer().Serialize(dict));
}
public bool IsReusable => false;
}
$.getJSON('JsonHandler.ashx', { name: '張三' }, function(data) {
alert(data.message); // .NET 2.0/3.0/3.5/4.0 皆為 { "message": "..." }
});
需在類別與方法加上屬性,自動序列化為 JSON。
<!-- .NET 2.0/3.0 -->
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" type="System.Web.Script.Services.ScriptHandlerFactory" validate="false"/>
</httpHandlers>
<!-- .NET 3.5/4.0 預設已包含,通常無需額外設定 -->
[WebService(Namespace = "https://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService] // 關鍵:允許腳本調用
public class JsonService : System.Web.Services.WebService {
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)] // 明確指定 JSON
public SortedDictionary<string, object> Save(string name) {
Context.Response.Cache.SetNoStore();
return new SortedDictionary<string, object> {
["message"] = string.IsNullOrEmpty(name) ? "無名氏" : $"你好 {name}, {DateTime.Now}"
};
}
}
| .NET 版本 | JSON 結構 | jQuery 取值 |
|---|---|---|
| 2.0 / 3.0 | { "message": "..." } | data.message |
| 3.5 / 4.0+ | { "d": { "message": "..." } } | data.d.message |
原因:3.5+ 引入 d 包裝防止 JSON 劫持攻擊。
| 維度 | ASHX | ASMX |
|---|---|---|
| 效能 | 極高(無管道開銷) | 略低(WebService 架構) |
| 開發體驗 | 手工序列化 | 強型別、自動序列化、WSDL 支援 |
| 適用場景 | 高併發 AJAX、簡單 API、檔案上傳 | 企業級服務、需文檔、跨語言調用 |
| 安全性 | 自行實作 | 內建 SOAP/JSON 切換、易整合驗證 |
維護舊專案時,ASHX 適合輕量端點,ASMX 適合結構化服務;新專案請直接採用 Web API 或 Minimal API。