首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET 建立 Web Service 與管理狀態

     編輯:關於ASP.NET

XML Web Service 繼承 WebService 基類即可存取 Session、Application 等 ASP.NET 內建狀態物件。

啟用 Session

預設 WebMethod **不支援** Session,需在屬性明確開啟:

[WebMethod(EnableSession = true)]
public int GetVisitCount()
{
    int count = (int)(Session["VisitCount"] ?? 0);
    Session["VisitCount"] = ++count;
    return count;
}

Application 狀態

無需額外設定,直接存取:

[WebMethod]
public int GetTotalUsers()
{
    return (int)(Application["TotalUsers"] ?? 0);
}

關鍵差異

特性SessionApplication
範圍單一用戶會話整個應用程式所有用戶
啟用方式[WebMethod(EnableSession=true)]自動可用
典型用途購物車、用戶偏好、驗證碼線上人數、全站公告、共用快取
叢集支援需 StateServer/SQLServer/Redis需外部分散式快取

用戶端支援 Cookie 前提

Session 依賴 Cookie 傳遞 SessionID。若用戶端禁用 Cookie,需在 web.config 設定 cookieless="UseUri" 將 SessionID 嵌入 URL。

完整 Web Service 範本

<%@ 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() { ... }
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved