如何跟踪用户在每个控制器或操作上花费的持续时间?

时间:2018-04-03 06:14:44

标签: c# .net asp.net-mvc

我对asp.net mvc很陌生,我想跟踪每个用户在控制器或actionResult上花费的时间。这就是他们留在网络应用程序的特定部分上的时间,例如他们花费多长时间浏览http://mywebappname/Resident/Index。这就是我到目前为止所做的......

 public class AuditAttribute : ActionFilterAttribute
{
    protected DateTime StarTime;
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        StarTime = DateTime.Now;

        base.OnActionExecuting(filterContext);
    }

    public override void OnResultExecuted(ResultExecutedContext executedContext)
    {
        // Stores the Request in an Accessible object
        var request = executedContext.HttpContext.Request;

        RouteData routeData = executedContext.RouteData;
        // Generate an audit
        Audit audit = new Audit()
        {
            // Your Audit Identifier     
            AuditId = Guid.NewGuid(),
            // Our Username (if available)
            UserName = (request.IsAuthenticated) ? executedContext.HttpContext.User.Identity.Name : "Anonymous",
            // The IP Address of the Request
            IPAddress = request.ServerVariables["HTTP_X_FORWARDED_FOR"] ?? request.UserHostAddress,
            // The URL that was accessed
            ExactAreaAccessed = request.RawUrl,
            // Creates our Timestamp
            Timestamp = DateTime.UtcNow,

            ControllerAccessed = (string)routeData.Values["controller"],

            ActionAccessed = (string)routeData.Values["action"],

            Duration = (DateTime.Now - StarTime),

            DateCreated = DateTime.Now
        };

        // Stores the Audit in the Database
        ApplicationDbContext context = new ApplicationDbContext();
        context.Audits.Add(audit);
        context.SaveChanges();

        // Finishes executing the Action as normal 
        base.OnResultExecuted(executedContext);
    }
}

但它没有给我预期的结果。请问我错过了什么?

0 个答案:

没有答案