1,新建网站,添加服务器控件
脚本:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!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>ASP.NET测试</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label ID="Label1" runat="server" Text="共点击次数:"></asp:Label> <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label> <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" /> </div> </form> </body> </html>
代码:
using System; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { int count = 0; Application.Lock(); if (Application["HitCounter"]!=null) { count = (int)Application["HitCounter"]; } count++; Application["HitCounter"] = count; Application.UnLock(); Label2.Text = count.ToString(); } protected void Button1_Click(object sender, EventArgs e) { Response.Write(DateTime.Now.ToString()); } }
2,解决方案-添加新项-全局应用程序类(Global.asax)
代码:
<%@ Application Language="C#" %> <script runat="server"> void Application_Start(object sender, EventArgs e) { //在应用程序启动时运行的代码 System.IO.StreamReader sr = System.IO.File.OpenText(Server.MapPath(".") + "\\count.txt"); Application.Lock(); Application["Dir"] = Server.MapPath("."); Application["HitCounter"] = sr.ReadLine(); Application["HitCounter"] = Convert.ToInt32(Application["HitCounter"]) + 1; Application.UnLock(); sr.Close(); } void Application_End(object sender, EventArgs e) { //在应用程序关闭时运行的代码 //System.IO.StreamWriter rw = System.IO.File.CreateText(Server.MapPath(".") + "\\count.txt"); System.IO.StreamWriter rw = System.IO.File.CreateText(Application["Dir"].ToString() + "\\count.txt"); Application.Lock(); rw.WriteLine(Application["HitCounter"]); Application.UnLock(); rw.Flush(); //写入 rw.Close(); } void Application_Error(object sender, EventArgs e) { //在出现未处理的错误时运行的代码 } void Session_Start(object sender, EventArgs e) { //在新会话启动时运行的代码 } void Session_End(object sender, EventArgs e) { //在会话结束时运行的代码。 // 注意: 只有在 Web.config 文件中的 sessionstate 模式设置为 // InProc 时,才会引发 Session_End 事件。如果会话模式 //设置为 StateServer 或 SQLServer,则不会引发该事件。 } </script>
3,保证网页目录内有文本count.txt,里面有一个数字,配置IIS目录权限,说不准我把EveryOne用户给加了,然后在
sytem.web表现中加入这行。
<system.web>
<identity impersonate="true"/>
</system.web>
4,发布网站后就可以看到结果
5,在cmd中输入iisreset /restart ,可见在iis重启后,依然可以保留其计数值