使用ASP.NET MVC3 實現一個訪問統計系統

來源:互聯網
上載者:User

      運營網站,我們經常需要分析使用者的行為、使用者的習慣,使用者看重網站的哪一部分,哪一部分是對使用者有用的之類的資訊,這些資訊從哪裡來,這時我們就需要用到訪問統計系統了。 網上已經有很多的統計系統,如站長統計、百度統計、Google分析之類的,別人的東西始終是別人的,為什麼我們不自己實現統計的功能呢,而且自己寫的可以實現一些特殊的功能,如登入,下單行為,能夠更好的融合自己的系統!

      下面我們就用ASP.NET MVC3來實現一個訪問統計系統!首先,使用程式產生一段js代碼,包括讀寫Cookie,及寫入一個唯一值到Cookie中,用來判斷獨立訪客者,再寫入訪問次數及上一個訪問頁面ID值;然後就是擷取用戶端時間,解析度之類的。

 

            string guid = Guid.NewGuid().ToString();            #region 產生js            html.Append("function WriteCookie(cookieName, cookieValue, expiry) {");  //js寫cookie            html.Append("  var expDate = new Date();");            html.Append("  if (expiry) {");            html.Append("    expDate.setTime(expDate.getTime() + expiry);");            html.Append("    document.cookie = cookieName + \"=\" + escape(cookieValue) + \"; path=/;expires=\" + expDate.toGMTString();");            html.Append("  }");            html.Append("  else {");            html.Append("    document.cookie = cookieName + \"=\" + escape(cookieValue) + \"; path=/;\"");            html.Append("  }");            html.Append("}");            html.Append("function ReadCookie(name) {");  //js讀取cookie            html.Append("    var cookieValue = \"\";");            html.Append("    var search = name + \"=\";");            html.Append("    if (document.cookie.length > 0) {");            html.Append("        offset = document.cookie.indexOf(search);");            html.Append("        if (offset != -1) {");            html.Append("            offset += search.length;");            html.Append("            end = document.cookie.indexOf(\";\", offset);");            html.Append("            if (end == -1)");            html.Append("                end = document.cookie.length;");            html.Append("            cookieValue = unescape(document.cookie.substring(offset, end))");            html.Append("        }");            html.Append("    }");            html.Append("    return cookieValue;");            html.Append("}");                       html.Append("DateFormatString = function(datetime, format) {");            html.Append("    var year = datetime.getFullYear();");            html.Append("    var month = datetime.getMonth()+1;");            html.Append("    var date = datetime.getDate();");            html.Append("    var hour = datetime.getHours();");            html.Append("    var minutes = datetime.getMinutes();");            html.Append("    var second = datetime.getSeconds();");            html.Append("    format = format.replace(/YY/g, year).replace(/MM/g, month).replace(/DD/g, date).replace(/hh/g, hour).replace(/mm/g, minutes).replace(/ss/g, second);");            html.Append("    return format;");            html.AppendLine("}");            html.Append("var cookieEnabled = (navigator.cookieEnabled) ? true : false;");  //判斷瀏覽器是否支援cookie            html.Append("if (typeof navigator.cookieEnabled == \"undefined\" && !cookieEnabled) {");            html.Append("    document.cookie = \"testcookie\";");            html.Append("    cookieEnabled = (document.cookie == \"testcookie\") ? true : false;");            html.Append("    document.cookie = \"\";");            html.Append("}");            html.Append("var firstshow;");            html.Append("var visittotal;");            html.Append("var isLogin;");            html.Append("var loginName;");            html.Append("if (cookieEnabled == true) {");            html.Append("    var HBCountShowCookie = ReadCookie(\"HBCountShowCookie\");");  //訪客瀏覽器唯一ID            html.Append("    var HBCountVisitTotalCookie = ReadCookie(\"HBCountVisitTotalCookie\");");  //訪客瀏覽次數            html.Append("    var HBClientIDCookie = ReadCookie(\"HBClientIDCookie\");");    //訪客上一個點擊頁面ID            html.Append("    var HBLoginNameCookie = ReadCookie(\"HBLoginNameCookie\");");  //記錄登入的使用者名稱            html.Append("    if (HBCountShowCookie == \"\") {");                        html.Append("        sparetime = 1000 * 60 * 60 * 24 * 3650;"); //有效期間為一年            html.Append("        WriteCookie('HBCountShowCookie', \"" + guid + "\", sparetime);");            html.Append("        HBCountShowCookie = ReadCookie(\"HBCountShowCookie\");");            html.Append("        firstshow = 1;");            html.Append("    }");            html.Append("    else {");            html.Append("        firstshow = 0;");            html.Append("    }");            html.Append("    if (HBCountVisitTotalCookie == \"\") {"); //遊客統計            html.Append("        sparetime = 1000 * 60 * 60 * 24 * 3650;");            html.Append("        WriteCookie('HBCountVisitTotalCookie', 1, sparetime);");            html.Append("        visittotal = 1;");            html.Append("    }");            html.Append("    else {");            html.Append("        if (firstshow == 1) {");            html.Append("            visittotal = parseInt(HBCountVisitTotalCookie) + 1;");            html.Append("            sparetime = 1000 * 60 * 60 * 24 * 3650;");            html.Append("            WriteCookie('HBCountVisitTotalCookie', visittotal, sparetime);");            html.Append("        }");            html.Append("        else {");            html.Append("            visittotal = parseInt(HBCountVisitTotalCookie);");            html.Append("        }");            html.Append("    }");            html.Append("    try {");            html.Append("       if (HBStat != undefined || HBStat.isLogin != undefined || HBStat.loginName != undefined) {"); //此為登入使用者統計            html.Append("            if (HBStat.isLogin == 1 && HBStat.loginName != \"\") {");            html.Append("                sparetime = 1000 * 60 * 60 * 24 * 120;");            html.Append("                WriteCookie('HBLoginNameCookie', HBStat.loginName, sparetime);");            html.Append("                HBLoginNameCookie = ReadCookie(\"HBLoginNameCookie\");");            html.Append("            }");            html.Append("            isLogin=HBStat.isLogin;");            html.Append("        }");            html.Append("        else{isLogin=0;}");            html.Append("    }");            html.Append("    catch (e) { isLogin=0; }");            html.Append("    loginName=HBLoginNameCookie;");            html.Append("} else {");  //不支援cookie            html.Append("    firstshow = 0;");            html.Append("    visittotal = 1;");            html.Append("    var HBCountShowCookie = \"\";");            html.Append("    isLogin=0;");            html.Append("    loginName=\"\";");            html.Append("}");            html.Append("var ly = escape(document.referrer);");            html.Append("var currweb = escape(location.href);");            html.Append("var d = new Date();");            html.Append("var currdate=DateFormatString(d,'YY-MM-DD hh:mm:ss');");            html.Append("var screenwidth=screen.width;");            html.Append("var screenheight=screen.height;");            html.Append("var screencolordepth=screen.colorDepth;");             html.Append("document.write('<script src=\"" + websiteUrl + "CountGet/?SiteID=" + SiteID + "&assort=" + assort + "&isLogin='+isLogin+'&loginName='+loginName+'&FirstShow='+firstshow+'&VisitTotal='+visittotal+'&Ly='+ly+'&CurrWeb='+currweb+'&cookid='+HBCountShowCookie+'&screenwidth=' + screenwidth + '&screenheight=' + screenheight + '&screencolordepth=' + screencolordepth + '&currdate='+currdate+'&ranstr=' +  Math.random() + '\"></script>');");            #endregion

 

產生之後再去執行下一個Action,用來寫入一些統計資料,如用戶端IP,瀏覽器資訊,訪問頁面來源,當前頁、訪問時間、離開時間等!根據上一個訪問頁面地址、當前地址及上一個訪問頁面ID來判斷是否是重新整理操作還是新的訪問頁面,如果是重新整理操作則寫入重新整理時間,否則寫入上一個頁面的離開時間,由於js的跨域問題,

            if (assort.Equals(0))            {                ly = Request.QueryString["Ly"];           //擷取來源URL                currWeb = Request.QueryString["CurrWeb"]; //擷取當前URL            }            else            {                ly = Request.ServerVariables["Http_Referer"];                currWeb = ly;            }            string firstShow = Request.QueryString["FirstShow"];   //是否第一次訪問            string visitTotal = Request.QueryString["VisitTotal"]; //擷取瀏覽次數              string ip = Helper.Utils.ClientIP();                   //擷取用戶端IP地址            string strAgent = Request.ServerVariables["HTTP_USER_AGENT"];            bool isAlexa = false;            if (strAgent.IndexOf("alexa") > -1)   //判斷是否安裝alexa工具列                isAlexa = true;            string browerName = Request.Browser.Browser;    //瀏覽器名稱            string browerVersion = Request.Browser.Version; //瀏覽器版本                        string os = Helper.Utils.GetClientOS();         //用戶端作業系統            string langage = Helper.Utils.GetLangage();     //用戶端語言            string spider = Helper.Utils.GetSpiderBot();    //搜尋引擎爬蟲資訊            bool isSpider = false;            if (!string.IsNullOrEmpty(spider))                isSpider = true;
HttpContext.Application.Lock();            ClickDataAccess clientBasic = new ClickDataAccess();            //重新整理操作  需要根據上一個地址和當前地址 來判斷            if (HttpContext.Application["HBCurrWeb_" + SiteID] != null                && HttpContext.Application["HBCurrWeb_" + SiteID].ToString().Equals(currWeb)                && HttpContext.Application["HBLy_" + SiteID] != null                && HttpContext.Application["HBLy_" + SiteID].ToString().Equals(ly)                && HttpContext.Application["HBClientId_" + SiteID] != null)            {                clientBasic.UpdateForRefresh(HttpContext.Application["HBClientId_" + SiteID]);                //Helper.Utils.CreateFile("~/Log/", DateTime.Now.ToString("yyyyMMddHHmmssffff") + "_" + SiteID + "重新整理.txt", writetext.ToString());            }            else            {                if (HttpContext.Application["HBClientId_" + SiteID] != null) //如果存在上一個頁面的ID值則寫入離開時間                    clientBasic.UpdateForLeaveTime(HttpContext.Application["HBClientId_" + SiteID]);                ClickAndVisitorsDataAccess clientData = new ClickAndVisitorsDataAccess();                string[] outParam = clientData.Save(client);                if (!string.IsNullOrEmpty(outParam[0]))                    HttpContext.Application["HBPublicId_" + SiteID] = outParam[0];                if (!string.IsNullOrEmpty(outParam[1]))                {                    HttpContext.Application["HBClientId_" + SiteID] = outParam[1];                    javaScript = "WriteCookie('HBClientIDCookie'," + int.Parse(outParam[1]) + ");";                }                HttpContext.Application["HBCurrWeb_" + SiteID] = currWeb;                HttpContext.Application["HBLy_" + SiteID] = ly;            }            HttpContext.Application.UnLock();            #endregion

這裡使用Application來儲存物件,當然也可以使用緩衝類來做.

  

暫時沒有解決離開當前網站時的離開時間,當然如果訪問統計系統的網域名稱和被統計的網站網域名稱是同一個頂級網域名稱,則可以做到這點!

       

      訪問統計系統的後台使用預存程序來統計分析資料,暫時唯寫了一部分功能,訪問統計系統也暫時只是一個demo,僅供大家學習參考!

項目原始碼:http://download.csdn.net/detail/jobily/3671987

                 http://down.51cto.com/data/263059

還是提供csdn就 51cto的,其他地址以後再附上,網站資料訪問的架構及一些預存程序經過很長的時間積累而成,花了我很多的心思,希望大家不要吝嗇自己的那點分,絕對值得你學習,此項目很多類及插入更新的預存程序都是另一個項目自動產生滴,關於自動產生、靈活性及多資料庫支援將會在以後文章中公開,敬請期待。 

     

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.