2010-08-14 34 views
2

我面臨着一個老問題,它讓我非常困惑。所以我需要你的建議來確保我一直在用正確的方式。 我的需求是算在我的網站訪問者的數量,所以我在Global.asax文件編碼:在網站中統計訪客總數的正確方法是什麼?

void Application_Start(object sender, EventArgs e) 
{ 
    // Get total visitor from database 
    long SiteHitCounter = 0; 
    int CurrentUsers = 0; 
    SiteHitCounter = MethodToGetTotalVisitorFromDatabase(); 
    Application["SiteHitCounter"] = SiteHitCounter; 
    Application["CurrentUsers"] = CurrentUsers; 
} 

void Application_End(object sender, EventArgs e) 
{ 
    // Update total visitor to database when application shutdown 
    MethodToUpdateTotalVisitorToDatabase((long)Application["SiteHitCounter"]); 
} 

void Session_Start(object sender, EventArgs e) 
{ 
    // Increase total visitor and online user 
    Application["SiteHitCounter"] = (long)Application["SiteHitCounter"] + 1; 
    Application["CurrentUsers"] = (int)Application["CurrentUsers"] + 1; 
} 

void Session_End(object sender, EventArgs e) 
{ 
    // Decrease online user 
    Application["CurrentUsers"] = (int)Application["CurrentUsers"] - 1; 
} 

然後,我用變量應用[「SiteHitCounter」]和應用[CurrentUsers「]另一個C#後面的代碼文件在網頁上顯示它們 我面臨的問題是,當我將它發佈到共享主機時,網站無法顯示正確的訪問者總數量

我需要你對此的建議。

謝謝, Tien

+0

只需使用http://www.google.com/analytics/並讓他們處理問題:) – 2010-08-14 15:29:37

回答

1

檢查鏈接..

Setting an Application("Counter") in the global.asax

您應該在更新之前鎖定變量,因爲它現在共享。

void Session_Start(object sender, EventArgs e) 
{ 
    // Increase total visitor and online user 
    Application.Lock(); 

    Application["SiteHitCounter"] = (long)Application["SiteHitCounter"] + 1; 
    Application["CurrentUsers"] = (int)Application["CurrentUsers"] + 1; 

    Application.UnLock(); 
} 

void Session_End(object sender, EventArgs e) 
{ 
    // Decrease online user 
    Application.Lock(); 

    Application["CurrentUsers"] = (int)Application["CurrentUsers"] - 1; 

    Application.UnLock(); 
} 

如果你想使它公平適用於IP檢查,以便沒有人可以進行多個會話。

+0

完美的阿扎爾,我會盡量實施後檢查IP。我現在會用你的東西。非常感謝! – 2010-08-14 06:31:42

+0

歡迎....如果答案滿足你的目的,然後接受答案,這將有助於他人嘗試正確的方法,他們的simmiler問題。謝謝 – Azhar 2010-08-14 07:04:12

2

您無法保證會話結束事件會觸發。你也應該調用application.lock來確保在更新計數器時沒有併發問題。此外,有可能是同一人將您的應用程序的生命週期內創建多個會話,所以你可能要添加IP地址檢查,以進一步提高精度

+0

哦,謝謝你的回答。 – 2010-08-14 05:36:08

1

訪問者是請求1頁的人。在請求之後,無法知道他們是否在您的網站上,就像他們正在閱讀您的網頁一樣。

會話從第一個請求的頁面開始,並在20分鐘後過期,即使用戶剛剛在會話的第1秒中請求了1頁然後離開。

因此,沒有真正的方法來了解您在特定時刻有多少訪問者。

您可以創建一個包含訪問IP地址的列表並註冊訪問時間。 然後,讓我們說20分鐘後,您可以使用計時器自行終止這些條目。它也會使來自同一IP的重複會話無效。

相關問題