Page generation time - ASP.Net MVC

前端 未结 3 471
遥遥无期
遥遥无期 2020-12-12 17:30

I\'m looking for a way to track how long it took for a page to be generated by the server. I know I can use Trace to track this but I need a way to display this per page.

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-12 18:21

    You can implement it like a ActionFilterAttribute

    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
    public class LoggingAttribute : ActionFilterAttribute
    {
        private readonly Stopwatch _sw;
    
        public LoggingAttribute()
        {
            _sw = new Stopwatch();
        }
    
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            _sw.Start();
            Debug.WriteLine("Beginning executing: " + GetControllerAndActionName(filterContext.ActionDescriptor));
        }
    
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            _sw.Stop();
            var ms = _sw.ElapsedMilliseconds;
    
            Debug.WriteLine("Finishing executing: " + GetControllerAndActionName(filterContext.ActionDescriptor));
            Debug.WriteLine("Time elapsed: "+ TimeSpan.FromMilliseconds(ms).TotalSeconds);
        }
    
        private string GetControllerAndActionName(ActionDescriptor actionDescriptor)
        {
            return actionDescriptor.ControllerDescriptor.ControllerName + " - " + actionDescriptor.ActionName;
        }
    }
    

    Decorate every controller or action-method with it and voila, it spit outs the text in debug.

    EDIT: If you want to print it on the page you could add this snippet to the OnActionExecuted method

    if(filterContext.Result is ViewResult) { //Make sure the request is a ViewResult, ie. a page
      ((ViewResult) filterContext.Result).ViewData["ExecutionTime"] = ms; //Set the viewdata dictionary
    }
    

    Now you have the executiontime saved in ViewData and can access it in the page.. I usually put it in the masterpage like this

    
    

提交回复
热议问题