ASP.NET/Application

维基教科书,自由的教学读本
跳到导航 跳到搜索

Application是System.Web.HttpApplication类的一个集合属性,用于保存所有用户的公共的数据信息。

在线用户统计的例子,定义在global.asax.cs中:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.IO; 
using System.Collections;
using System.ComponentModel;  
/// Global 的摘要说明。
namespace WebApplication1
{

    public class Global : System.Web.HttpApplication
    {
        /// 必需的设计器变量。
        private System.ComponentModel.IContainer components = null;

        private FileStream fileStream;
        private StreamReader reader;//读字符流
        private StreamWriter writer;//写字符流
        public Global()
        {
            //InitializeComponent();
        }
        protected void Application_Start(object sender, EventArgs e)
        {
            Application["CurrentGuests"] = 0;//初始为0;
            fileStream = File.Open(Server.MapPath("counts.text"), FileMode.OpenOrCreate);//文件不存在,创建文件
            reader = new StreamReader(fileStream);//要读取的完整路径
            Application["AllGuests"] = Convert.ToInt32(reader.ReadLine()); //从当前流中读取一行字符并将数据作为字符串返回
            reader.Close();//关闭流
        }

        protected void Session_Start(object sender, EventArgs e)
        {
            Application.Lock();//同步,避免同时写入

            Application["CurrentGuests"] = (int)Application["CurrentGuests"] + 1;//总在线用户数
            Application["AllGuests"] = (int)Application["AllGuests"] + 1;//访问网站的总用户数
            fileStream = new FileStream(Server.MapPath("counts.text"), FileMode.OpenOrCreate, FileAccess.ReadWrite);//
            writer = new StreamWriter(fileStream);//实现一个写入流,使其以一种特定的编码向流中写入字符
            writer.WriteLine(Application["AllGuests"].ToString());//把访问网站的总用户数再次写入到文件
            writer.Close();//关闭写入流

            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 Session_End(object sender, EventArgs e)
        {
            Application.Lock();
            Application["CurrentGuests"] = (int)Application["CurrentGuests"] - 1;//总在线用户数量-1
            Application.UnLock();
        }

        protected void Application_End(object sender, EventArgs e)
        {

        }
    }
}

在WebForm1.aspx.cs中使用:

    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
           bool b =  IsPostBack;
            this.Label1.Text = "正在访问站点的用户数:" + Application["CurrentGuests"].ToString();
            this.Label2.Text = "访问过站点的总用户数:" + Application["AllGuests"].ToString();
        }
    }