Global.asax文件(也稱為ASP.NET應用程序文件)是ASP.NET Web應用程序中的一個重要文件,它允許您處理應用程序級別和會話級別的事件。下面介紹如何利用Global.asax來實現各種功能。
Global.asax基本結構
<%@ Application Language="C#" %>
<script runat="server">void Application_Start(object sender, EventArgs e){// 應用程序啟動時運行的代碼}void Application_End(object sender, EventArgs e){// 應用程序關閉時運行的代碼}void Application_Error(object sender, EventArgs e){// 發生未處理錯誤時運行的代碼}void Session_Start(object sender, EventArgs e){// 新會話啟動時運行的代碼}void Session_End(object sender, EventArgs e){// 會話結束時運行的代碼}
</script>
常用功能實現
1. 應用程序初始化
void Application_Start(object sender, EventArgs e)
{// 初始化全局變量Application["TotalUserSessions"] = 0;Application["CurrentUsers"] = 0;// 注冊路由(適用于Web Forms)RegisterRoutes(System.Web.Routing.RouteTable.Routes);// 初始化緩存或其他服務InitializeApplicationCache();
}
2. 會話跟蹤
void Session_Start(object sender, EventArgs e)
{// 用戶會話開始時增加計數Application.Lock();Application["TotalUserSessions"] = (int)Application["TotalUserSessions"] + 1;Application["CurrentUsers"] = (int)Application["CurrentUsers"] + 1;Application.UnLock();
}void Session_End(object sender, EventArgs e)
{// 用戶會話結束時減少當前用戶數Application.Lock();Application["CurrentUsers"] = (int)Application["CurrentUsers"] - 1;Application.UnLock();
}
3. 全局錯誤處理
void Application_Error(object sender, EventArgs e)
{Exception ex = Server.GetLastError();// 記錄錯誤日志LogError(ex);// 清除錯誤Server.ClearError();// 重定向到自定義錯誤頁面Response.Redirect("~/Error.aspx");
}private void LogError(Exception ex)
{string logFile = Server.MapPath("~/App_Data/ErrorLog.txt");string message = $"{DateTime.Now}: {ex.Message}\n{ex.StackTrace}\n\n";System.IO.File.AppendAllText(logFile, message);
}
4. URL重寫和路由
void Application_Start(object sender, EventArgs e)
{RegisterRoutes(System.Web.Routing.RouteTable.Routes);
}private void RegisterRoutes(System.Web.Routing.RouteCollection routes)
{// Web Forms路由示例routes.MapPageRoute("ProductRoute","products/{category}/{id}","~/ProductDetails.aspx");// 其他路由規則...
}
5. 請求預處理
protected void Application_BeginRequest(object sender, EventArgs e)
{// 在每個請求開始時執行的操作HttpContext.Current.Response.AddHeader("X-Application-Name", "MyApp");// 實現URL重寫string path = Request.Path.ToLower();if (path.Contains("/oldpage.aspx")){Context.RewritePath("/newpage.aspx");}
}
6. 響應后處理
protected void Application_EndRequest(object sender, EventArgs e)
{// 在每個請求結束時執行的操作if (Response.StatusCode == 404){Response.Clear();Server.Transfer("~/NotFound.aspx");}
}
7. 實現全局授權檢查
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{// 檢查用戶權限等if (Context.User != null && Context.User.Identity.IsAuthenticated){// 可以在這里實現自定義的角色管理}
}
注意事項
-
性能考慮:Global.asax中的代碼會在每個請求或應用程序生命周期中執行,確保代碼高效
-
線程安全:訪問Application對象時使用Lock/UnLock
-
異常處理:確保全局錯誤處理不會引發新的異常
-
狀態管理:Application狀態對所有用戶共享,Session狀態是用戶特定的
通過合理利用Global.asax文件,您可以實現許多應用程序級別的功能,從而增強ASP.NET Web應用的功能性和健壯性。