ASP.NET WebService(ASMX)雖屬舊世代技術,但在既有系統維護中仍廣泛存在。本文系統整理 [WebService] 與 [WebMethod] 屬性的完整參數與實戰用法。
[WebService] 屬性[WebService(
Description = "服務描述文字",
Namespace = "https://yourdomain.com/webservice", // 唯一命名空間,避免衝突
Name = "MyWebService" // 服務顯示名稱
)]
public class MyService : System.Web.Services.WebService { ... }
service name,預設為類別名。[WebMethod] 六大屬性[WebMethod(
Description = "方法說明",
EnableSession = false, // 是否啟用 Session
MessageName = "AlternateName",// 方法多載別名
TransactionOption = TransactionOption.Disabled, // 交易選項
CacheDuration = 0, // 快取秒數
BufferResponse = true // 回應緩衝
)]
public string MyMethod(string param) { ... }
在 WSDL 與測試頁面顯示的方法說明,便於 API 文檔生成。
false(預設):無 Session,效能較好。true:啟用 HttpContext.Current.Session,可儲存用戶狀態。[WebMethod(EnableSession = true, Description = "登入驗證")]
public string Login(string username) {
if (username == "admin") Session["User"] = username;
return Session["User"] != null ? "已登入" : "未登入";
}
WebService 不支援傳統多載,需透過 MessageName 區分同名方法。
[WebMethod(MessageName = "AddInt")]
public int Add(int a) { return a; }
[WebMethod(MessageName = "AddTwoInt")]
public int Add(int a, int b) { return a + b; }
// 客戶端呼叫時使用 AddInt、AddTwoInt
注意:.NET Framework 2.0 以上版本不再支援此屬性。現代應用請改用 System.Transactions.TransactionScope 或資料庫層面交易控制。
| 值 | 行為(歷史參考) |
|---|---|
| Disabled / NotSupported | 不在交易中執行 |
| Supported | 若呼叫端有交易則加入,否則不建立 |
| Required / RequiredNew | 強制在新交易中執行 |
0:不快取。Cache-Control: no-cache,ASP.NET 會忽略伺服器端快取設定。true(預設):完整回應內容緩衝後一次傳送,效能較好。false:以 16KB 區塊串流傳送,適用於大量資料(如大檔案下載、報表串流),避免記憶體壓力。<%@ WebService Language="C#" Class="AuthService" %>
using System.Web.Services;
[WebService(Namespace = "https://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class AuthService : WebService {
[WebMethod(EnableSession = true, Description = "用戶登入驗證")]
public string Login(string username) {
if (username == "admin") {
Session["User"] = username;
return "登入成功";
}
Session.Remove("User");
return "登入失敗";
}
[WebMethod(EnableSession = true, Description = "檢查登入狀態")]
public string CheckStatus() {
return Session["User"] != null ? "已登入:" + Session["User"] : "未登入";
}
}
掌握 WebMethod 六大屬性,能精準控制 WebService 行為。新專案建議改用 ASP.NET Core Web API 或 gRPC,但維護舊系統時,本文可作為快速查閱手冊。