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