萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

jQuery AJAX 調用 ASP.NET WebForms 頁面靜態 WebMethod 完整實戰指南

核心前提:WebMethod 必須是 public static


// 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; }
}

jQuery AJAX 標準調用模板


$.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. 請求方法必須 POSTtype: "GET"type: "POST"
2. Content-Type 必須 application/jsoncontentType: "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: nulldata: "{}"

返回值解析:.d 包裝器

ASP.NET AJAX 為防 XSS,將返回值包裹在 d 屬性中:


// 服務端返回 "Hello"
// 客戶端收到: {"d":"Hello"}
// 取值: response.d

ASP.NET Core / MVC Controller 不包裹,直接返回 JSON。

啟用 Session 的 WebMethod


[WebMethod(EnableSession = true)]
public static string GetSessionData() {
    return HttpContext.Current.Session["UserId"]?.ToString() ?? "Guest";
}

**注意**:啟用 Session 會鎖定 Session 狀態,並發請求會串行化,影響並發性能。能不用則不用。

完整可運行示例:單頁面自調用 (無獨立 .asmx)



<%@ 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; } }

錯誤診斷清單

  1. HTTP 500:檢查服務端錯誤日志 / `xhr.responseText` 中的 `Message`、`StackTrace`。
  2. 返回整個 HTML 頁面:URL 錯誤(如寫成 `WebForm2.aspx.cs/Method`)、未標記 `[WebMethod]`、方法非 `public static`。
  3. 「Invalid JSON primitive」:`data` 不是合法 JSON 字符串。
  4. 參數全為 null/default:JSON 屬性名與方法參數名不匹配(區分大小寫)。
  5. 跨域報錯:WebForms 不支持 CORS 原生配置,需同域或反向代理/JSONP(舊)。

現代替代:ASP.NET Core / Web API

  • WebForms WebMethod 屬於**舊技術棧** (ASP.NET AJAX 3.5 時代)。
  • 新項目請直接使用 **ASP.NET Core Controller / Minimal API**,原生支持屬性路由、模型綁定、Swagger、依賴注入、異步、OpenAPI。
  • 遷移路徑:`.aspx` → `.cshtml` (Razor Pages) 或 `Controller` + `return Json()`。

結語

掌握 **POST + application/json + JSON.stringify + response.d** 四要素,即可在 WebForms 中穩定調用 WebMethod。**新項目請毫不猶豫選擇 ASP.NET Core**,避開 WebForms 的 ViewState、Page Lifecycle、PostBack 等歷史包袱,擁抱現代雲原生開發體驗。

copyright © 萬盛學電腦網 all rights reserved