ASP.NET中使用Application对象实现简单在线人数统计

注:最近在复习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浏览器访问应用,得到下图所示结果。

ASP.NET中使用Application对象实现简单在线人数统计

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjwpfs.html