65-100 application对象 程序案例
前端代码
课程只有一部分,所以影响了后面的完整测试。修改前端代码后,可以完整展示
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DeWeb2.aspx.cs" Inherits="Asp.NetDemo2.Demo05.DeWeb2" %> DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>title> head> <body> <form id="form1" runat="server"> <div> 您是本网站第0位访客 <asp:Button ID="Ita" runat="server" OnClick="btnClear_Clear" Text="清除当前用户的session信息" /> div> form> body> html>
global
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Security; using System.Web.SessionState; namespace Asp.NetDemo2.Demo05 { public class Global : System.Web.HttpApplication { protected void Application_Start(object sender, EventArgs e) { Application.Lock(); Application["UserVisit"] = 0;// 网站被访问的次数 Application["CurrentUsers"] = 0;// 在线的人数 Application.UnLock(); // 解锁 } protected void Session_Start(object sender, EventArgs e) { Application.Lock(); Application["UserVisit"] =(int)Application["UserVisit"]+1;// Application["CurrentUsers"] = (int)Application["CurrentUsers"]+1;// Application.UnLock(); // 解锁 } protected void Session_End(object sender, EventArgs e) { //在会话结束时 运行的代码 // 注意:在web.config文件中,把session state模式设置为inPro时才引发此事件 Application.Lock(); Application["CurrentUsers"] = (int)Application["CurrentUsers"] -1; Application.UnLock(); // 解锁 } protected void Application_BeginRequest(object sender, EventArgs e) { } protected void Application_AuthenticateRequest(object sender, EventArgs e) { } protected void Application_Error(object sender, EventArgs e) { } protected void Application_End(object sender, EventArgs e) { } } }
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Asp.NetDemo2.Demo05 { public partial class DeWeb2 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (IsPostBack) { // Ita 是按钮的id定义。 不定义,要报错。 this.Ita.Text = "您是本网站第" + Application["UserVisit"].ToString() + "位访客!" + "当前在线人数:" + Application["CurrentUsers"].ToString(); } } // 清除当前用户的session protected void btnClear_Clear(object sender, EventArgs e) { Session.Abandon(); } } }
效果:
写正确了,可以记录网站人数,访客人数。 就是这个application对象的作用。