Global.asax文件的應用 使用到全局變量顯示網站的總訪問人數以及當前訪問人數
數據庫:create database MyHost
use Myhost
create table num
(
total int
)
insert into num values(1)
新建一個頁面 放置兩個label
this.Label1.Text = "總訪問人數:" + Application["total"].ToString();
this.Label2.Text = "當前在線人數:" + Application["online"].ToString();
<%@ Application Language="C#" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<script runat="server">
void Application_Start(object sender, EventArgs e)
{
// 在應用程序啓動時運行的代碼
//DB dbm = new DB();
SqlConnection connection =new SqlConnection("server=.;database=MyHost;uid=sa;pwd=;");//dbm.getcon();
connection.Open();
SqlCommand cmd = new SqlCommand("select total from num",connection);
Application["total"] = Convert.ToInt32(cmd.ExecuteScalar());
Application["online"] = 0;
}
void Application_End(object sender, EventArgs e)
{
// 在應用程序關閉時運行的代碼
//SqlConnection connection = DB.createCon();//象上面一樣修改
SqlConnection connection =new SqlConnection("server=.;database=MyHost;uid=sa;pwd=;");//dbm.getcon();
connection.Open();
SqlCommand cmd = new SqlCommand("update num set total="+Application["total"], connection);
cmd.ExecuteNonQuery();
}
void Application_Error(object sender, EventArgs e)
{
// 在出現未處理的錯誤時運行的代碼
}
void Session_Start(object sender, EventArgs e)
{
// 在新會話啓動時運行的代碼
Session.Timeout = 1;
Application.Lock();
Application["online"] = (int)Application["online"] + 1;
Application["total"] = (int)Application["total"] + 1;
Application.UnLock();
}
void Session_End(object sender, EventArgs e)
{
// 在會話結束時運行的代碼。
// 注意: 只有在 Web.config 文件中的 sessionstate 模式設置爲
// InProc 時,纔會引發 Session_End 事件。如果會話模式設置爲 StateServer
// 或 SQLServer,則不會引發該事件。
Application.Lock();
Application["online"] = (int)Application["online"] - 1;
Application.UnLock();
}
</script>