// WebForm2.aspx.cs
using System.Web.Services;
[WebMethod] // 或 [WebMethod(EnableSession = true)] 需要 Session
public static string GetUserName() {
return "張三"; // 自動序列化為 JSON: {"d":"張三"}
}
// 需要參數版本
[WebMethod]
public static UserInfo GetUser(int id, string token) {
return UserService.Get(id, token);
}
public class UserInfo {
public int Id { get; set; }
public string Name { get; set; }
public DateTime LastLogin { get; set; }
}
$.ajax({
type: "POST", // 必須 POST
contentType: "application/json; charset=utf-8", // 必須 JSON
url: "WebForm2.aspx/GetUserName", // 頁面名/方法名
data: "{}", // 必須是 JSON 字符串,無參數也要 "{}"
dataType: "json", // 預期返回 JSON
success: function(response) {
// ASP.NET 3.5+ 返回格式: { "d": "實際返回值" }
var result = response.d;
console.log("用戶名:", result);
$("#lblUser").text(result);
},
error: function(xhr, status, error) {
console.error("AJAX 失敗:", status, error, xhr.responseText);
}
});
| 鐵律 | 錯誤示例 | 正確示例 |
|---|---|---|
| 1. 請求方法必須 POST | type: "GET" | type: "POST" |
| 2. Content-Type 必須 application/json | contentType: "application/x-www-form-urlencoded" | contentType: "application/json; charset=utf-8" |
| 3. data 必須是 JSON 字符串 | data: {id:1} (對象) / data: "id=1" (表單) | data: JSON.stringify({id:1}) 或 '{"id":1}' |
| 4. 無參數也要傳 "{}" | data: "" / data: null | data: "{}" |
ASP.NET AJAX 為防 XSS,將返回值包裹在 d 屬性中:
// 服務端返回 "Hello"
// 客戶端收到: {"d":"Hello"}
// 取值: response.d
ASP.NET Core / MVC Controller 不包裹,直接返回 JSON。
[WebMethod(EnableSession = true)]
public static string GetSessionData() {
return HttpContext.Current.Session["UserId"]?.ToString() ?? "Guest";
}
**注意**:啟用 Session 會鎖定 Session 狀態,並發請求會串行化,影響並發性能。能不用則不用。
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Services" %>
// 客戶端
var dto = { User: { Id: 1, Name: "Li" }, Options: { Detail: true } };
$.ajax({
// ...
data: JSON.stringify(dto), // 必須 stringify
success: function(r) { /* r.d 為服務端返回對象 */ }
});
// 服務端參數名需與 JSON 屬性名完全一致 (大小寫敏感)
[WebMethod]
public static ResultDto Process(UserDto User, OptionsDto Options) { ... }
public class UserDto { public int Id { get; set; } public string Name { get; set; } }
public class OptionsDto { public bool Detail { get; set; } }
掌握 **POST + application/json + JSON.stringify + response.d** 四要素,即可在 WebForms 中穩定調用 WebMethod。**新項目請毫不猶豫選擇 ASP.NET Core**,避開 WebForms 的 ViewState、Page Lifecycle、PostBack 等歷史包袱,擁抱現代雲原生開發體驗。