开发者

Anyone have any suggestions on how I can do server side web tracking with MVC?

I would like to put in some place som开发者_JS百科e 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.


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;

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜