views:

48

answers:

2

I have an aspx page which counts every visit and creates a cookie. But if I use OutputCache page counts only the first visitor who requested the page. How can I prevent this bug?

Page directive:

<%@ OutputCache Duration="1200" VaryByParam="mode;page;sid;tid" %>

Codebehind:

protected void Page_Load(object sender, EventArgs e)
{
    //Load single post data

    #region Hit Counter
    //hit counter lasts during session
    if (Session["LastHit" + postId] == null)
    {
        cmmnd.CommandText = "UPDATE Posts SET Hits=Hits+1 WHERE PostID=@PostID;";
        cmmnd.ExecuteNonQuery();
        Session["LastHit" + postId] = 1;
    }
    #endregion
}
+2  A: 

This isn't a bug, but by design. The page is not re-processed if it is in the cache and "the cached output is still valid". You can run code during this validation phase and this could help you perform the task of counting the visits and adding it to a cookie. The following might be of help:

Waleed Al-Balooshi
+2  A: 

What is the point of this count? Marketting information? Use a lightweight analytics counter from script or an image in the page, not mixed in with generating the page itself. The bug is that you're adding extra work to the busier requests, instead of giving the extra work its own request.

Jon Hanna
Just count blog post hits.
HasanGursoy
In that case I wouldn't even bother with an analytics counter, but rely on parsing the IIS logs. Why record data that is already recorded? If you really cared about who was re-viewing fully-cached pages (rather than on-server cached) then you could use the analytics counter trick, or use a service like google analytics (why should you suffer the performance headache of having sessions turned on when they can?).
Jon Hanna