c#在线人数和访问次数终极版实现

历尽多少次的修改,终于得到终极版本。感觉自己真笨!废话少说,上源代码:

1、Global.asax文件中

public void Application_Start(Object S, EventArgs E)

{

Application["Counter"] = 0;

//'第一次启动Application时将CurrentUsers归零

Application["CurrentUsers"] = 0;

}

public void Session_Start(Object S, EventArgs E)

{

//'On_line标志设成False,表示第一次连接到该站点

Session["On_line"] = false; // '第一次连接,所以赋值false

Session["On_line2"] = false; //'避免多人连接时候在没有超时又再重新加载页面出错准备。详细见jishuqi.inc的on_line2

//'指定Session的TimeOut属性(默认值是20分钟)

Session.Timeout = 10;

Application.Lock();

//'每有一人连接,CurrentUsers便加一,并且解锁

Application["CurrentUsers"] = System.Convert.ToInt32(Application["CurrentUsers"]) + 1;

Application.UnLock();

}

public void Session_End(Object S, EventArgs E)

{

Application.Lock();

//'每有一人离线,CurrentUsers便减一

Application["CurrentUsers"] = System.Convert.ToInt32(Application["CurrentUsers"]) - 1;

Application.UnLock();

// 注意: 只有在 Web.config 文件中的 sessionstate 模式设置为

// InProc 时,才会引发 Session_End 事件。如果会话模式设置为 StateServer

// 或 SQLServer,则不会引发该事件

}

public void Application_End(Object S, EventArgs E)

{

}

2、在count.aspx文件中

protected void Page_Load(object sender, EventArgs e)

{

Label5.Text = Request.UserHostAddress;//ip地址

Label1.Text = Application["CurrentUsers"].ToString();

// Label2.Text = Application["countall"].ToString();

//以下为修改后的计数器

string app_path = Server.MapPath(".") + "\\" + "jsq_ms.cnt";

//判断是否存在计数器文件

if (File.Exists(app_path) == false)//

{

StreamWriter txtWriter = File.CreateText(Server.MapPath(".") + "\\" + "jsq_ms.cnt");//生成文件,开始记录

txtWriter.WriteLine(1);//写行,定为1

txtWriter.Close();

}

string counter_file = app_path;

string HitRate, tempNo, imgName; // 'HitRate是点击率

StreamReader txtReader = File.OpenText(counter_file);

HitRate = txtReader.ReadLine().Trim();//读行

txtReader.Close();

//如果符合条件

if (Session["On_line2"] !=null )//20110519原先这里判断为==null,要更改为!=null才可以执行,写计数的行 {

Session["On_line2"] =true ;

tempNo = System.Convert.ToString(System.Convert.ToInt32(HitRate) + 1);//中间取得值

StreamWriter txtWriter = File.CreateText(counter_file);

txtWriter.WriteLine(tempNo);//写行

txtWriter.Close();

}

//Label2.Text = HitRate;//文字形式输出

if (!IsPostBack) //对付分页重复输出 所以问是否第一次加载,这句很重要

{

for (int i = 1; i <= HitRate.Length; i++)//图形方式输出

{

imgName = HitRate.Substring(i - 1, 1);//因为从0开始计算位置的,所以i-1

// Response.Write("<img src='images/" + imgName + ".gif'>");

Label2.Text = Label2.Text + "<img src='images/" + imgName + ".gif'>";

}

}

}

小结:Global.asax放在根目录就可以。其他的ascx可重复使用组件可以放在文件夹,也可以同一根目录

Global.asax 文件是 ASP.NET 应用程序的中心点。它提供无数的事件来处理不同的应用程序级任务,比如用户身份验证、应用程序启动以及处理用户会话等。你应该熟悉这个可选文件,这样就可以构建出健壮的ASP.NET 应用程序。

Global.asax 文件,有时候叫做 ASP.NET 应用程序文件,提供了一种在一个中心位置响应应用程序级或模块级事件的方法。你可以使用这个文件实现应用程序安全性以及其它一些任务。让我们详细看一下如何在应用程序开发工作中使用这个文件。 概述 Global.asax 位于应用程序根目录下。虽然 Visual Studio .NET 会自动插入这个文件到所有的 ASP.NET 项目中,但是它实际上是一个可选文件。删除它不会出问题——当然是在你没有使用它的情况下。.asax 文件扩展名指出它是一个应用程序文件,而不是一个使用 aspx 的 ASP.NET 文件。 Global.asax 文件被配置为任何(通过 URL 的)直接 HTTP 请求都被自动拒绝,所以用户不能下载或查看其内容。ASP.NET 页面框架能够自动识别出对Global.asax 文件所做的任何更改。在 Global.asax 被更改后ASP.NET 页面框架会重新启动应用程序,包括关闭所有的浏览器会话,去除所有状态信息,并重新启动应用程序域。 编程 Global.asax 文件继承自HttpApplication 类,它维护一个HttpApplication 对象池,并在需要时将对象池中的对象分配给应用程序。

事件被触发的顺序是:

·Application_BeginRequest

·Application_AuthenticateRequest

·Application_AuthorizeRequest

·Application_ResolveRequestCache

·Application_AcquireRequestState

·Application_PreRequestHandlerExecute

·Application_PreSendRequestHeaders

·Application_PreSendRequestContent

·<<所写的c#或vb执行代码>>

·Application_PostRequestHandlerExecute

·Application_ReleaseRequestState

·Application_UpdateRequestCache

·Application_EndRequest

这些事件常被用于安全性方面。

下面这个 C# 的例子演示了不同的Global.asax 事件,该例使用Application_Authenticate 事件来完成通过 cookie 的基于表单(form)的身份验证。此外,Application_Start 事件填充一个应用程序变量,而Session_Start 填充一个会话变量。Application_Error 事件显示一个简单的消息用以说明发生的错误。

protected void Application_Start(Object sender, EventArgs e)

{ Application["Title"] = "Builder.com Sample";

}

protected void Session_Start(Object sender, EventArgs e)

{ Session["startValue"] = 0;

}

protected void Application_AuthenticateRequest(Object sender, EventArgs e)

{ // Extract the forms authentication cookie string cookieName = FormsAuthentication.FormsCookieName; HttpCookie authCookie = Context.Request.Cookies[cookieName];

if(null == authCookie)

{ // There is no authentication cookie.

return;

}

FormsAuthenticationTicket authTicket = null;

try

{

authTicket = FormsAuthentication.Decrypt(authCookie.Value);

}

catch(Exception ex)

{ // Log exception details (omitted for simplicity) return;

}

if (null == authTicket)

{ // Cookie failed to decrypt.

return;

} // When the ticket was created, the UserData property was assigned // a pipe delimited string of role names. string[2] roles roles[0] = "One" roles[1] = "Two" //Create an Identity object FormsIdentity id = new FormsIdentity( authTicket ); // This principal will flow throughout the request. GenericPrincipal principal = new GenericPrincipal(id, roles); // Attach the new principal object to the current HttpContext object Context.User = principal;

}

protected void Application_Error(Object sender, EventArgs e)

{

Response.Write("Error encountered.");

}

这个例子只是很简单地使用了一些Global.asax 文件中的事件;重要的是要意识到这些事件是与整个应用程序相关的。