2009-07-03 87 views
1

每一個我的網頁加載它的時候運行在頁面的Page_Load事件例行其背後遞增1如何從運行停止Page_Load事件,如果刷新頁面

我的問題一的觀看次數即使使用刷新重新加載頁面,該例程也會運行。

如果頁面已被特定用戶在當前會話中查看,如何停止運行此例程?

我想我可以使用:

If Not Page.IsPostBack Then 
(run the routine) 

,但它似乎並沒有工作。

我需要使用會話狀態或cookie等嗎?

回答

1

您可以記錄用戶是否在會話中訪問該頁面。您可以在頁面路徑下的會話中放置一個bool。這樣它將適用於個人用戶,並且會在會話期間工作。

要記錄用戶訪問過的,你可以做以下頁面:

HttpContext.Current.Session[pagePath] = true; 

,並得到用戶是否訪問過的頁面,你可以這樣做:

bool hasUserVisitedPage = (bool)HttpContext.Current.Session[pagePath]; 

這裏是如何它會在您的頁面加載中合併到一起:

protected void Page_Load(object sender, EventArgs e) 
{ 
    //set the default for whether the user visited the page 
    bool hasUserVisitedPage = false; 
    //get the path of the page 
    string pagePath = HttpContext.Current.Request.Url.LocalPath; 

    //find out if the user visited the page by looking in the session 
    try { hasUserVisitedPage = (bool)HttpContext.Current.Session[pagePath]; } 
    //we don't care if the value wasn't present (and therefore didn't cast) 
    catch {} 

    //if the user hasn't visited the page before 
    if (!hasUserVisitedPage) 
    { 
     //record that the page has now been visited 
     HttpContext.Current.Session[pagePath] = true; 

     //put the rest of your load logic here... 
    } 
} 

如果您想將此技術nique在多個頁面上我將這個功能封裝到一個輔助類中,所以你不會重複自己。

public static class PageHelper 
{ 
    public static bool hasPageBeenViewed() 
    { 
     //set the default for whether the user visited the page 
     bool hasUserVisitedPage = false; 
     //get the path of the page 
     string pagePath = HttpContext.Current.Request.Url.LocalPath; 

     //find out if the user visited the page by looking in the session 
     try { hasUserVisitedPage = (bool)HttpContext.Current.Session[pagePath]; } 
     //we don't care if the value wasn't present (and therefore didn't cast) 
     catch {} 

     //if the user hasn't visited the page before 
     if (!hasUserVisitedPage) 
     { 
      //record that the page has now been visited 
      HttpContext.Current.Session[pagePath] = true; 
     } 

     return hasUserVisitedPage; 
    } 
} 

然後,它會極大地簡化了負載邏輯如下: (它會給你的邏輯在一箇中心位置是,如果你需要改變它這將是非常方便的好處)

protected void Page_Load(object sender, EventArgs e) 
{ 
    //if the user hasn't visited the page before 
    if (!PageHelper.hasPageBeenViewed()) 
    {    
     //put the rest of your load logic here... 
    } 
} 
2

If Not Page.IsPostback只會幫助用戶點擊該頁面上的按鈕。如果用戶只刷新頁面(如使用F5),它將不起作用。 問題是

  • 你要添加到計數器,如果用戶回來的頁面,他一直在自己的網站其他頁面後(即首頁 - > productpage - >主頁)與否。

您可以使用字典並將其存儲在用戶的會話中。該詞典將是一個類型爲Dictionary<string, int>的詞典。當用戶訪問該頁面時,您檢索字典並查看是否已有當前頁面+ querystring(字符串Key)的條目。

如果沒有,添加它。然後根據是否要增加該頁面的計數(如果用戶在首次進入另一頁面後重新訪問該頁面時增加計數器(或不))。

您可以檢查用戶的另一個網址來用:Request.UrlReferrer