1

I would like to put in some place some very basic web tracking for my MVC application. I'd like to do this on the server side and I am wondering if anyone has any knowledge of some simple classes that I could use to help me with this.

I'd like to track the following things: The User's IP Address, What page they requested, and what country they are from, as well as the DateTime stamp.

George Stocker
  • 57,289
  • 29
  • 176
  • 237
Marie
  • 2,283
  • 2
  • 14
  • 5
  • what do you want to track? errors? service calls? do you mean tracing? need a bit more information about this – stack72 Jun 17 '11 at 15:29
  • Sorry I didn't add enough information. What I would like to track is page requests. Tracking the page requested and the country that it was requested from along with the date. – Marie Jun 17 '11 at 15:47

1 Answers1

2

Yes, you can intercept this in the controller for each request:

If you want the page the user requested:

Request.RawUrl //Gives the current and complete URL the user requested

If you want the Country it was requested from, you can get the IP address of the user and then use a ready-made function to look up where it's from:

Request.UserHostAddress

You can also get all the route values the user has passed in; to get a more complete picture of how they got to where they are.

public class MyController : Controller
{
    public ActionResult Home()
    {
        var userIP = Request.UserHostAddress;
        var requestedUrl = Request.UserHostAddress;
        var routeValues = this.ControllerContext.RouteData.Route.GetRouteData(HttpContext);
        var requestedDateTime = DateTime.Now;
    }
}

Now, you'd have to put this on each action, and that seems silly, so why not have this happen for everything that's executed?

protected virtual void OnActionExecuting(
    ActionExecutingContext filterContext)
{
    var userIP = filterContext.HttpContext.Request.UserHostAddress;
    var requestedUrl = filterContext.HttpContext.Request.UserHostAddress;
    var routeData = ((MvcHandler)filterContext.HttpContext.CurrentHandler).RequestContext.RouteData.Route.GetRouteData(filterContext.HttpContext);
    var requestedDateTime = DateTime.Now;

}
Community
  • 1
  • 1
George Stocker
  • 57,289
  • 29
  • 176
  • 237