注:最近在復習ASP.NET,為了加深印象,會制作一些小的demo程序,分享給大家。
1 新建ASP.NET網站,編輯Global.asax文件,修改後的文件內容如下所示。
<%@ Application Language="C#" %>
<script runat="server">
void Application_Start(object sender, EventArgs e)
{
// 在應用程序啟動時運行的代碼
Application["CurrentUserCount"] = 0;
}
void Application_End(object sender, EventArgs e)
{
// 在應用程序關閉時運行的代碼
}
void Application_Error(object sender, EventArgs e)
{
// 在出現未處理的錯誤時運行的代碼
}
void Session_Start(object sender, EventArgs e)
{
// 在新會話啟動時運行的代碼
Application.Lock();
Application["CurrentUserCount"] = (int)Application["CurrentUserCount"] + 1;
Application.UnLock();
}
void Session_End(object sender, EventArgs e)
{
// 在會話結束時運行的代碼。
// 注意: 只有在 Web.config 文件中的 sessionstate 模式設置為 InProc 時,才會引發 Session_End 事件。
// 如果會話模式設置為 StateServer
// 或 SQLServer,則不會引發該事件。
Application.Lock();
Application["CurrentUserCount"] = (int)Application["CurrentUserCount"] - 1;
Application.UnLock();
}
</script>
2 修改Web.config文件,增加如下配置節點,新增的配置節點位<system.web></system.web>節點下。
復制代碼 代碼如下:
<sessionState mode="InProc" timeout="1" cookieless="false"/>
3 在Default.aspx文件中添加一個標簽來顯示當前在線人數。
復制代碼 代碼如下:
protected void Page_Load(object sender, EventArgs e)
{
this.Label1.Text = Application["CurrentUserCount"].ToString();
}
4 先後使用IE和Chrome浏覽器訪問應用,得到下圖所示結果。
