Tom Ax
Tom Ax

Reputation: 576

ASP.net MVC Logging Page Views

Is there an easy way to log every page hit by any user. I am thinking this will sit within the global.asax.cs file, so that I can write to a db table the URL of the page being hit.

Upvotes: 3

Views: 2375

Answers (2)

Tom Ax
Tom Ax

Reputation: 576

I've found a way to complete this problem which seems to fit my purpose.

I use the PostAuthenticateRequestHandler method, as it is called for every page hit. I ignore any empty path and just "/" as these are not actual pages hit.

//in global.asax.cs file

private void PostAuthenticateRequestHandler(object sender, EventArgs e)
{
   ///...///

   string extension = this.Context.Request.CurrentExecutionFilePathExtension;
   string path = this.Context.Request.CurrentExecutionFilePath;

   if (extension == string.Empty && path != "/")
   {
   PageVisitedLogModel pageVisitedLogModel = new PageVisitedLogModel
   {
       DateVisited = DateTime.Now,
       IPAddress = this.Context.Request.UserHostAddress,
       PageURL = this.Context.Request.RawUrl,
       Username = this.Context.User.Identity.Name
   };

   //then writes to log
   DataHelper.UpdatePageVisitedLog(pageVisitedLogModel);
}
}

Upvotes: 4

Rob West
Rob West

Reputation: 5241

One way to do this would be to use a global action filter, as in this example. This allows you to run some code for any action in your solution.

Upvotes: 0

Related Questions