简体   繁体   中英

Writing to database on session_End event

I'm writing a HttpModule to track page views for a user based on their current session.

I have the module working fine except for when the user abandons their session. Example scenario:

  • Session timeout is 20 minutes
  • User browses site for 15 minutes
  • User navigates away from site
  • Session end event will now not be triggered for this user as they have left the site

I want to hook into the Session End event so that I can bulk update the page views for a user rather than doing this each time they hit a page (not as good performance wise).

Is there a way of detecting when this happens and then triggering an event/piece of code to log the views?

Sample code incase needed:

public void Init(HttpApplication application)
{
    application.PostRequestHandlerExecute += application_PostRequestHandlerExecute;
    SessionStateModule session = (SessionStateModule)application.Modules["Session"];
    session.Start += session_Start;
    session.End += session_End;
}

void session_End(object sender, EventArgs e)
{
    Visitor visitor = HttpContext.Current.Session["visitor"] as Visitor;

    if (visitor != null)
    {
        foreach (PageItem page in visitor.Pages)
        {
            page.UpdatePageViews();
        }
    }
}

I know this probably isn't in line with the solution as it stands, but perhaps you could look at another solution for tracking usage, such as Google Analytics - since they have put a lot of effort into their platform.

You can also integrate your solution with Google Analytics to pull summary information back into yours as required. This means you also don't need to store all the tracking information locally, but rather simply make requests via their API as required.

I found the API difficult to integrate with but have it working in a solution now.

If you have to do the tracking locally, why not do this asynchronously so you're not tying up the UI thread - that way the performance impact should be minimal?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM