Ngôn ngữ ASP.NET - Tập tin Global.asax
Tập tin Global.asax
Tập tin Global.asax được dùng để:
- Khai báo và khởi tạo giá trị cho các biến Application, Session.
- Viết xử lý cho các sự kiện của 2 đối tượng Application và Session.
Các sự kiện trong tập tin Global.asax.
Application_Start: Chỉ xảy ra một lần đầu tiên khi bất kỳ trang nào trong ứng dụng được gọi.
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
Application["Hits"] = 0;
Application["Sessions"] = 0;
Application["TerminatedSessions"] = 0;
Application.Lock();
System.IO.StreamReader rd = new System.IO.StreamReader(Server.MapPath("sl.txt"));
string s = rd.ReadLine();
rd.Close();
Application.UnLock();
Application.Add("HitCounters", s);
}
Session_Start: Xảy ra khi có một người dùng mới yêu cầu đến bất kỳ trang aspx của ứng dụng. Khi Session_Start xảy ra, một giá trị duy nhất (SessionID) sẽ được tạo cho người dùng, và giá trị này được sử dụng để quản lý người dùng trong quá trình làm việc với ứng dụng.
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
Application.Lock();
Application["Sessions"] = (int)Application["Sessions"] + 1;
Application.UnLock();
Application["HitCounters"] = int.Parse(Application["HitCounters"].ToString ()) + 1;
System.IO.StreamWriter wr = new System.IO.StreamWriter(Server.MapPath("sl.txt"));
wr.Write(Application["HitCounters"]);
wr.Close();
}
Application_BeginRequest: Xảy ra khi mỗi khi có Postback về Server.
Application_Error: Xảy ra khi có lỗi phát sinh trong quá trình thi hành.
Session_End: Xảy ra khi phiên làm việc không có gởi yêu cầu hoặc làm tươi trang aspx của ứng dụng web trong một khoảng thời gian (mặc định là 20 phút).
void Session_End(object sender, EventArgs e)
{
// Code that runs when a session ends.
// Note: The Session_End event is raised only when the sessionstate mode
// is set to InProc in the Web.config file. If session mode is set to StateServer
// or SQLServer, the event is not raised.
Application.Lock();
Application["TerminatedSessions"] = (int)Application["TerminatedSessions"] + 1;
Application.UnLock();
}
Application_End: Xảy ra khi dừng hoạt động của WebServer. Ví dụ xử lý ghi nhận thông tin Số lượt truy cập vào cơ sở dữ liệu (nếu cần).