常用伺服器資訊取得方式
// 機器與網域
string machineName = Server.MachineName;
string serverDomain = Request.ServerVariables["SERVER_NAME"];
string serverPort = Request.ServerVariables["SERVER_PORT"];
string serverSoftware = Request.ServerVariables["SERVER_SOFTWARE"]; // IIS 版本
// 路徑資訊
string virtualPath = Request.FilePath; // /App/Page.aspx
string physicalPath = Request.PhysicalPath; // D:\Web\App\Page.aspx
string appVirtualRoot = Request.ApplicationPath; // /App
string appPhysicalRoot = Request.PhysicalApplicationPath; // D:\Web\App\
// 平台與執行環境
string osDir = Environment.SystemDirectory; // C:\Windows\System32
string netVersion = Environment.Version.ToString(); // 4.0.30319.42000
string culture = CultureInfo.InstalledUICulture.EnglishName; // Chinese (Traditional, Taiwan)
DateTime now = DateTime.Now;
TimeSpan uptime = TimeSpan.FromMilliseconds(Environment.TickCount);
TimeSpan scriptTimeout = TimeSpan.FromSeconds(Server.ScriptTimeout);
// 請求標頭
foreach (string key in Request.Headers.AllKeys)
{
string value = Request.Headers[key]; // Connection, Accept, User-Agent...
}
// 伺服器變數
foreach (string key in Request.ServerVariables.AllKeys)
{
string value = Request.ServerVariables[key]; // ALL_HTTP, PATH_INFO, URL, HTTP_USER_AGENT...
}
關鍵 ServerVariables 對照表
| 變數 | 說明 | 範例 |
| SERVER_NAME | 伺服器主機名稱或 IP | www.example.com |
| SERVER_PORT | 伺服器監聽埠 | 80 / 443 |
| SERVER_SOFTWARE | IIS 版本 | Microsoft-IIS/10.0 |
| REQUEST_METHOD | HTTP 方法 | GET / POST |
| PATH_INFO | 虛擬路徑 | /App/Page.aspx |
| URL | 完整 URL (含查詢字串) | /App/Page.aspx?id=1 |
| HTTP_USER_AGENT | 瀏覽器 UA 字串 | Mozilla/5.0... |
| HTTP_REFERER | 來源頁面 | https://google.com/... |
| REMOTE_ADDR | 用戶端 IP | 203.0.113.45 |
| HTTP_X_FORWARDED_FOR | 代理鏈原始 IP | 198.51.100.1, 203.0.113.45 |
實務應用場景
- 健康檢查端點:回傳機器名、.NET 版本、啟動時間、磁碟空間。
- 錯誤日誌豐富化:自動附加 UA、IP、Referer、ServerVariables。
- 多租戶/灰度發布:依 `SERVER_NAME` 或 `HTTP_HOST` 判斷租戶。
- 安全審計:記錄 `HTTP_X_FORWARDED_FOR` 鏈路、異常 UA。
注意事項
- `Request.ServerVariables` 在 IIS 7+ 整合模式需 `` 或移除 `managedHandler` 前置條件。
- `Environment.TickCount` 為有號 32 位整數,約 24.9 天會溢位歸零,**不適合長期運行系統的正確運算時間**;改用 `PerformanceCounter("System", "System Up Time")` 或 WMI `Win32_OperatingSystem.LastBootUpTime`。
- 生產環境避免在頁面直接輸出所有 ServerVariables(洩露內部資訊),僅供診斷頁面/管理後台使用。