1.建一个表,标的第一列字段Number,int类型
2.在web.config编辑连接数据库的字符串:
<connectionStrings>
<add name="northwindConnectionString" connectionString="DataSource=.;
InitialCatalog=northwind;User ID=sa;Password=sa" providerName="System.Data.SqlClient" />
</connectionStrings>
3.添加新项--->全局应用程序集:Global.asax,文件内容如下:
<%@ Application Language="C#" Debug=true%>
<%@ Import Namespace="System.Data.SqlClient" %>
<script runat="server">
void Application_Start(object sender, EventArgs e)
{
// 在应用程序启动时运行的代码
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["northwindConnectionString"].ConnectionString;
con.Open();
SqlCommand cmd = new SqlCommand("select * from users", con);
int count = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
Application["total"] = count;
Application["online"] = 0;
}
void Application_End(object sender, EventArgs e)
{
// 在应用程序关闭时运行的代码
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["northwindConnectionString"].ConnectionString;
con.Open();
SqlCommand cmd = new SqlCommand("update users set Number=" + Application["total"].ToString(), con);
cmd.ExecuteNonQuery();
con.Close();
}
void Application_Error(object sender, EventArgs e)
{
//在出现未处理的错误时运行的代码
}
void Session_Start(object sender, EventArgs e)
{
// 在新会话启动时运行的代码
Session.Timeout = 5; //设置Session的有效时间,可根据需要修改
Application.Lock();
Application["total"] = (int)Application["total"] + 1;
Application["online"] = (int)Application["online"] + 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>
4.调用
调用方式1----在源代码里编辑:
<asp:Label ID="Label1" runat="server">当前在线 <font color=red><%=Application["online"]%></font> 人</asp:Label>
<asp:Label ID="Label2" runat="server">总访问量: <font color=red><%=Application["total"]%></font> </asp:Label>
调用方式2----在设计编辑:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
int i = (int)Application.Get("total");
Label2.Text = "在线人数:" + i.ToString();
}
//也可以这样:
// Label2.Text = "总访问人数" + Application["total"].ToString();
}
本文作者:网友 来源:网络