.net在Global.asax里面轻松的实现站点访问统计

来源:互联网 发布:银河号事件 知乎 编辑:程序博客网 时间:2024/05/16 15:51
具体的原理是:
在application开始的时候从一个文件里读取数字放进一个Application里,
这样主要是防止在站点重启的时候清零了
然后就是Session_Start,变量+1,
在Application_End时候再更新数据一次,
代码如下:

<%@ Application Language="C#" %>
<%@ Import  Namespace = "System.Data.SqlClient" %>

<script runat="server">

    void Application_Start(object sender, EventArgs e)
    {
        // 在应用程序启动时运行的代码
        SqlConnection con = new SqlConnection();
        con.ConnectionString = ConfigurationManager.ConnectionStrings["TongJiConnectionString"].ConnectionString;
        con.Open();
        SqlCommand cmd = new SqlCommand("select * from liulantongji", con);
        int count = Convert.ToInt32(cmd.ExecuteScalar());
        con.Close();
        Application["total"] = count;
        
    }
    
    void Application_End(object sender, EventArgs e)
    {
        //  在应用程序关闭时运行的代码
        SqlConnection con = new SqlConnection();
        con.ConnectionString = ConfigurationManager.ConnectionStrings["TongJiConnectionString"].ConnectionString;
        con.Open();
        SqlCommand cmd = new SqlCommand("update liulantongji set totalnum =" + Application["total"].ToString(), con);
        cmd.ExecuteNonQuery();
        con.Close();
      
    }
        
    void Application_Error(object sender, EventArgs e)
    {
        // 在出现未处理的错误时运行的代码

    }

    void Session_Start(object sender, EventArgs e)
    {
        Session["admin"] = null;
        Session["admintype"] = null;  
        // 在新会话启动时运行的代码
        Application.Lock();
        Application["total"] =Convert.ToInt32(Application["total"] )+ 1;      
        Application.UnLock();

    }

    void Session_End(object sender, EventArgs e)
    {
        // 在会话结束时运行的代码。
        // 注意: 只有在 Web.config 文件中的 sessionstate 模式设置为
        // InProc 时,才会引发 Session_End 事件。如果会话模式设置为 StateServer
        // 或 SQLServer,则不会引发该事件。
        
      

    }
      
</script>
原创粉丝点击