每個 ASP.NET 應用程式啟動時都需要執行初始化工作:讀取設定檔、建立資料庫連線字串、啟動 SQL 依賴快取、預熱快取資料等。雖然眾所周知在 Global.asax 的 Application_Start 執行,但錯誤的例外處理方式卻能導致應用程式進入「殭屍狀態」——初始化失敗卻繼續接受請求,隨後爆發連串詭異錯誤。
public static class AppInitializer {
public static ConnectionStringSettings MyNorthwindConnectionSetting { get; private set; }
public static void Init() {
LoadConnectionString();
SetSqlDependency();
OthersInit();
}
static void LoadConnectionString() {
var setting = ConfigurationManager.ConnectionStrings["MyNorthwind"];
if (setting == null)
throw new ConfigurationErrorsException("缺少 MyNorthwind 連線字串設定。");
if (string.IsNullOrEmpty(setting.ConnectionString))
throw new ConfigurationErrorsException("MyNorthwind 連線字串內容為空。");
if (string.IsNullOrEmpty(setting.ProviderName))
throw new ConfigurationErrorsException("MyNorthwind 未指定 ProviderName。");
MyNorthwindConnectionSetting = setting;
}
static void SetSqlDependency() {
// 略過版本檢查與 Service Broker 啟用檢查
SqlDependency.Start(MyNorthwindConnectionSetting.ConnectionString);
}
static void OthersInit() {
// 載入基礎快取資料、檢查上傳目錄、初始化第三方 SDK 等
}
}
void Application_Start(object sender, EventArgs e) {
try {
AppInitializer.Init();
} catch (Exception ex) {
LogException(ex); // 僅記錄日誌,不重新拋出!
// 應用程式繼續啟動,但關鍵依賴未就緒
}
}
MyNorthwindConnectionSetting 為 null),觸發 NullReferenceException 或資料庫連線失敗。void Application_Start(object sender, EventArgs e) {
// 直接呼叫,不捕獲例外
AppInitializer.Init();
// 若 Init() 拋出例外,ASP.NET 會:
// 1. 記錄詳細堆疊追蹤到事件檢視器 / 應用程式日誌
// 2. 將應用程式標記為「啟動失敗」
// 3. 後續請求直接回傳 500.30 (ANCM Startup Failure) 或黃色死機畫面
// 4. 運維監控系統可立即偵測到應用程式異常
}
在 Web.config 設定:
<system.webServer>
<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="500" />
<error statusCode="500" path="/StartupError.html" responseMode="File" />
</httpErrors>
</system.webServer>
// HealthCheck.ashx 或 Controller Action
public void ProcessRequest(HttpContext context) {
try {
// 輕量檢查:資料庫連線、快取服務、關鍵靜態資源是否就緒
using (var conn = new SqlConnection(AppInitializer.MyNorthwindConnectionSetting.ConnectionString)) {
conn.Open();
}
context.Response.StatusCode = 200;
context.Response.Write("Healthy");
} catch {
context.Response.StatusCode = 503;
context.Response.Write("Unhealthy");
}
}
Application_Start 中絕不捕獲初始化例外。private set,防止後續意外修改。遵循此原則,應用程式啟動狀態將始終處於「完全就緒」或「明確失敗」兩種確定狀態,消除灰色地帶帶來的運維惡夢。