WCF 會話 提供跨多次呼叫的狀態保持機制。透過 SessionMode、IsInitiating/IsTerminating 與 InstanceContextMode.PerSession,可精確控制會話生命週期與狀態範圍。
| 值 | 說明 |
|---|---|
| Allowed (預設) | 綁定支援會話則使用,不支援則不使用 |
| Required | 強制要求會話綁定,否則擲出例外 |
| NotAllowed | 禁止會話 |
| 屬性 | 說明 |
|---|---|
| IsInitiating | 標記啟動會話的操作 (預設 true) |
| IsTerminating | 標記結束會話的操作 (預設 false) |
[ServiceContract(SessionMode = SessionMode.Required)]
public interface IHello {
[OperationContract(IsInitiating = true, IsTerminating = false)]
void StartSession();
[OperationContract(IsInitiating = false, IsTerminating = true)]
void StopSession();
[OperationContract(IsInitiating = false, IsTerminating = false)]
int Counter();
[OperationContract(IsInitiating = false, IsTerminating = false)]
string GetSessionId();
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class Hello : IHello {
private int _counter;
public void StartSession() => _counter = 0;
public void StopSession() => _counter = 0;
public int Counter() => ++_counter;
public string GetSessionId() => OperationContext.Current.SessionId;
}
wsHttpBinding 支援安全會話與可靠會話:
<wsHttpBinding>
<binding name="SessionManagementBindingConfiguration" receiveTimeout="00:00:10">
<reliableSession enabled="true" />
<security>
<message establishSecurityContext="true" /> <!-- WS-SecureConversation -->
</security>
</binding>
</wsHttpBinding>
receiveTimeout:非活動逾時 (此處 10 秒),相當於 Session 過期時間reliableSession:WS-ReliableMessaging 可靠會話establishSecurityContext:WS-SecureConversation 安全會話,建立安全內容權杖 (SCT)public partial class InstanceMode_Hello : Page {
SessionManagemenSvc.HelloClient _proxy;
protected void Page_Load(object sender, EventArgs e) {
if (Session["proxy"] == null)
Session["proxy"] = new SessionManagemenSvc.HelloClient();
_proxy = Session["proxy"] as SessionManagemenSvc.HelloClient;
}
protected void btnStartSession_Click(object sender, EventArgs e) {
_proxy.StartSession();
}
protected void btnCounter_Click(object sender, EventArgs e) {
ScriptManager.RegisterStartupScript(this, GetType(), "js",
$"alert('計數器:{_proxy.Counter()}')", true);
}
protected void btnGetSessionId_Click(object sender, EventArgs e) {
ScriptManager.RegisterStartupScript(this, GetType(), "js",
$"alert('SessionId:{_proxy.GetSessionId()}')", true);
}
protected void btnStopSession_Click(object sender, EventArgs e) {
_proxy.StopSession();
}
}
<wsHttpBinding>
<binding name="SessionManagementBindingConfiguration">
<reliableSession enabled="true" />
<security>
<message establishSecurityContext="true" />
</security>
</binding>
</wsHttpBinding>
StartSession(),初始化計數器,建立會話StopSession(),結束會話,後續呼叫將失敗receiveTimeout (10 秒) 無活動 → 伺服器自動終止會話| InstanceContextMode | 會話行為 |
|---|---|
| PerCall | 不支援會話狀態 (每呼叫新實例) |
| PerSession | 每個 Session 一個實例,支援會話狀態 |
| Single | 全域單一實例,所有 Session 共享 (需自行隔離狀態) |
SessionMode.Required 確保綁定支援IsInitiating/IsTerminating 定義明確的會話邊界receiveTimeout 避免資源洩漏wsHttpBinding 或 netTcpBinding 獲得完整會話支援WCF 會話機制讓無狀態的 Web 服務也能輕鬆實現有狀態的商務流程,是建構企業級應用的重要基石。