萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET 網站訪客計數器實作:Application 物件與文字檔持久化

核心機制

  • Application 物件:應用程式層級狀態,跨所有使用者共享,適合存放全站訪客計數。
  • Global.asax 事件:`Application_Start` 初始化 (從檔案讀取)、`Session_Start` 遞增計數、`Application_End` 持久化存檔。
  • 文字檔儲存:簡單無資料庫相依,適合中小型網站;高流量建議改用 Redis、資料庫或效能計數器。

前端頁面 Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head runat="server">
    <title>網站訪客計數器</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <table style="width:269px; height:75px; background-color:gray; color:lime; font-weight:bold; font-size:30px; text-align:center;">
                <tr><td>網站訪問量</td></tr>
                <tr>
                    <td style="background-color:gray;">
                        你是第 
                        <asp:Label ID="onlineCount" runat="server" Width="62px"><%= Application["onlinecount"] %></asp:Label> 
                        位訪問者
                    </td>
                </tr>
            </table>
        </div>
    </form>
</body>
</html>

Global.asax 完整程式碼

<%@ Application Language="C#" %>
<%@ Import Namespace="System.IO" %>
<script runat="server">

    void Application_Start(object sender, EventArgs e)
    {
        int count = 0;
        string filePath = Server.MapPath("~/count.txt");

        // 讀取歷史計數
        if (File.Exists(filePath))
        {
            using (StreamReader sr = File.OpenText(filePath))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    if (int.TryParse(line, out int parsed))
                        count = parsed; // 取最後一行有效數字
                }
            }
        }

        Application["onlinecount"] = count;
    }

    void Session_Start(object sender, EventArgs e)
    {
        // 每新 Session 遞增
        Application.Lock();
        Application["onlinecount"] = (int)Application["onlinecount"] + 1;
        Application.UnLock();
    }

    void Application_End(object sender, EventArgs e)
    {
        // 應用程式結束時寫回檔案
        string filePath = Server.MapPath("~/count.txt");
        int count = (int)Application["onlinecount"];
        
        try
        {
            using (StreamWriter sw = new StreamWriter(filePath, false)) // false = 覆寫
            {
                sw.WriteLine(count);
            }
        }
        catch (Exception ex)
        {
            // 記錄錯誤
        }
    }

</script>

關鍵細節與改良建議

議題說明改良方向
Application.Lock/UnLock 多執行緒環境下避免競爭條件 必要,但會序列化存取,高併發下成瓶頸
Session_Start 觸發時機 瀏覽器關閉後 Session 逾時 (預設 20 分鐘) 才會產生新 Session 非即時「線上人數」,僅為「歷史造訪人次」
文字檔 I/O 競爭 多執行個體 (Web Farm) 或高頻寫入會衝突 改用資料庫 `UPDATE Counter SET Count = Count + 1` 或 Redis `INCR`
Application 重置 AppPool 回收、修改 Web.config、部署新版本皆會重置 持久化到外部儲存體 (DB/Redis/檔案) 可跨重啟保留
搜尋引擎爬蟲 會產生大量 Session 導致計數虛高 在 Session_Start 中檢查 User-Agent 過濾已知 Bot

進階版:使用資料庫原子操作 (無鎖、支援 Web Farm)

// Global.asax.cs (Code-behind 模式)
public class Global : HttpApplication
{
    protected void Session_Start(object sender, EventArgs e)
    {
        // 呼叫資料庫預存程序或直接執行原子 SQL
        using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Default"].ConnectionString))
        {
            conn.Open();
            // SQL Server 範例
            using (var cmd = new SqlCommand("UPDATE SiteStats SET VisitCount = VisitCount + 1 WHERE Id = 1; SELECT VisitCount FROM SiteStats WHERE Id = 1", conn))
            {
                int newCount = (int)cmd.ExecuteScalar();
                Application["onlinecount"] = newCount; // 同步更新記憶體供前端顯示
            }
        }
    }
}

現代架構建議

  • 客戶端渲染:前端呼叫 API 取得計數,減少伺服器端渲染邏輯。
  • 分散式快取:Redis `INCR` + 定期持久化到 DB,高效能、跨節點共享。
  • 分析平台:Google Analytics、Matomo、Azure Application Insights 等專業分析工具取代自建計數器。

總結

Application 物件 + 文字檔是入門級訪客計數器的經典實作,理解其生命週期、執行緒同步與持久化時機至關對掌握 ASP.NET 狀態管理基本功。實務專案請根據流量規模、架構拓撲選擇適合的儲存後端,並注意爬蟲過濾與計數定義 (PV vs UV) 的業務語意差異。

copyright © 萬盛學電腦網 all rights reserved