傳統 ASP.NET Web Service (`.asmx`) 預設回傳 XML。若需回傳 JSON 供前端 AJAX 呼叫,需手動序列化並設定 `Response.ContentType`。本文提供三種實作方式:`JavaScriptSerializer` (內建)、`Json.NET` (推薦)、`ScriptMethod` 屬性簡化輸出,並說明前端 jQuery 呼叫細節。
[WebService(Namespace = "https://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService] // 允許腳本調用 (啟用 JSON 回傳)
public class MyService : System.Web.Services.WebService
{
[WebMethod]
public void GetUserInfo(string userId)
{
// 1. 業務邏輯取得資料
var user = UserService.GetById(userId);
if (user == null)
{
ReturnError("用戶不存在");
return;
}
// 2. 序列化為 JSON (使用 Json.NET 推薦)
string json = Newtonsoft.Json.JsonConvert.SerializeObject(user, new Newtonsoft.Json.JsonSerializerSettings
{
ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver(), // 駝峰命名
DateFormatString = "yyyy-MM-dd HH:mm:ss",
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore
});
// 3. 輸出 JSON
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/json; charset=utf-8";
HttpContext.Current.Response.Write(json);
HttpContext.Current.Response.End(); // 關鍵:結束回應,避免輸出 XML 宣告
}
private void ReturnError(string message)
{
var error = new { success = false, message };
string json = Newtonsoft.Json.JsonConvert.SerializeObject(error);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/json; charset=utf-8";
HttpContext.Current.Response.Write(json);
HttpContext.Current.Response.End();
}
}
[WebService(Namespace = "https://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class MyService : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = false)] // 強制 JSON、POST
public UserInfo GetUserInfo(string userId)
{
// 直接回傳物件,ASP.NET AJAX 自動序列化為 JSON
return UserService.GetById(userId) ?? throw new Exception("用戶不存在");
}
// 複雜型別回傳
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public PagedResult SearchUsers(string keyword, int page, int pageSize)
{
return UserService.Search(keyword, page, pageSize);
}
}
注意:`ScriptMethod` 使用內建 `JavaScriptSerializer`,序列化效能較差、不支援駝峰命名、日期格式固定為 `/Date(1234567890)/`、循環參考會拋出異常。複雜場景建議用方式一。
<%@ WebHandler Language="C#" Class="UserHandler" %>
using System.Web;
using Newtonsoft.Json;
public class UserHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json; charset=utf-8";
string action = context.Request.QueryString["action"] ?? "list";
try
{
object result;
switch (action)
{
case "get":
string id = context.Request.QueryString["id"];
result = UserService.GetById(id);
break;
case "list":
int page = int.Parse(context.Request.QueryString["page"] ?? "1");
int size = int.Parse(context.Request.QueryString["size"] ?? "20");
result = UserService.GetPaged(page, size);
break;
default:
throw new ArgumentException("未知 action");
}
string json = JsonConvert.SerializeObject(new { success = true, data = result },
new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() });
context.Response.Write(json);
}
catch (Exception ex)
{
string json = JsonConvert.SerializeObject(new { success = false, message = ex.Message });
context.Response.Write(json);
}
}
public bool IsReusable => false;
}
| 項目 | 手動 Response.Write (方式一) | ScriptMethod (方式二) | ASHX (方式三) |
|---|---|---|---|
| 序列化器 | 自訂 (Json.NET 推薦) | JavaScriptSerializer (內建) | 自訂 (Json.NET 推薦) |
| 日期格式 | 可控 (yyyy-MM-dd) | 固定 /Date(ms)/ | 可控 |
| 命名慣例 | 可控 (CamelCase) | PascalCase (屬性名) | 可控 |
| 循環參考 | 可設定忽略 | 拋出異常 | 可設定忽略 |
| 錯誤處理 | 完全自訂 | 自動包裝 SOAP Fault | 完全自訂 |
| 測試便利性 | 瀏覽器直接開啟 .asmx?op=... 會顯示 XML 測試頁 | 同左 | 瀏覽器直接開啟 .ashx 顯示 JSON |
總結:ASMX 回傳 JSON **推薦方式一 (手動 Json.NET + Response.End)**,擁有完全序列化控制權、最佳效能、標準日期/命名格式。簡單場景可用方式二 `ScriptMethod`。新專案建議直接用 **ASP.NET Core Web API** 或 **ASHX** 替代 ASMX,架構更現代、輕量、易測試。