任何人对如何使用MVC进行服务器端网络跟踪有任何建议?

时间:2011-06-17 15:26:41

标签: asp.net-mvc

我想在某些地方为我的MVC应用程序添加一些非常基本的Web跟踪。我想在服务器端这样做,我想知道是否有人知道我可以用来帮助我的一些简单的类。

我想跟踪以下内容:用户的IP地址,他们请求的页面,他们来自哪个国家/地区,以及日期时间戳。

1 个答案:

答案 0 :(得分:2)

是的,你可以在控制器中为每个请求拦截这个:

如果您想要用户请求的页面:

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

如果您想要来自的国家/地区,您可以获取该用户的IP地址和then use a ready-made function to look up where it's from

Request.UserHostAddress

您还可以获取用户传递的所有路线值;更全面地了解他们如何到达目的地。

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;
    }
}

现在,你必须把它放在每个动作上,这看起来很愚蠢,所以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;

}