XML Web Service 繼承 WebService 基類即可存取 Session、Application 等 ASP.NET 內建狀態物件。
預設 WebMethod **不支援** Session,需在屬性明確開啟:
[WebMethod(EnableSession = true)]
public int GetVisitCount()
{
int count = (int)(Session["VisitCount"] ?? 0);
Session["VisitCount"] = ++count;
return count;
}
無需額外設定,直接存取:
[WebMethod]
public int GetTotalUsers()
{
return (int)(Application["TotalUsers"] ?? 0);
}
| 特性 | Session | Application |
|---|---|---|
| 範圍 | 單一用戶會話 | 整個應用程式所有用戶 |
| 啟用方式 | [WebMethod(EnableSession=true)] | 自動可用 |
| 典型用途 | 購物車、用戶偏好、驗證碼 | 線上人數、全站公告、共用快取 |
| 叢集支援 | 需 StateServer/SQLServer/Redis | 需外部分散式快取 |
Session 依賴 Cookie 傳遞 SessionID。若用戶端禁用 Cookie,需在 web.config 設定 cookieless="UseUri" 將 SessionID 嵌入 URL。
<%@ WebService Language="C#" Class="MyService" %>
using System.Web.Services;
[WebService(Namespace = "https://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class MyService : WebService
{
[WebMethod(EnableSession = true)]
public string SessionTest() { ... }
[WebMethod]
public string AppTest() { ... }
}