代码之家  ›  专栏  ›  技术社区  ›  LiamB

页面生成时间-ASP.NETMVC

  •  15
  • LiamB  · 技术社区  · 15 年前

    我正在寻找一种方法来跟踪服务器生成页面所需的时间。我知道我可以使用跟踪跟踪这一点,但我需要一种方法来显示每页。

    它的ASP.NETMVC2

    3 回复  |  直到 15 年前
        1
  •  14
  •   JOBG    14 年前

    是的,Derin建议是在ASP.NEt应用程序中执行此操作的标准方法,我只建议添加一个if,这样不会干扰非HTML响应:

    public class PerformanceMonitorModule : IHttpModule
    {
    
        public void Init(HttpApplication context)
        {
            context.PreRequestHandlerExecute += delegate(object sender, EventArgs e)
            {
                //Set Page Timer Star
                HttpContext requestContext = ((HttpApplication)sender).Context;
                Stopwatch timer = new Stopwatch();
                requestContext.Items["Timer"] = timer;
                timer.Start();
                 };
            context.PostRequestHandlerExecute += delegate(object sender, EventArgs e)
            {
    
                HttpContext httpContext = ((HttpApplication)sender).Context;
                HttpResponse response = httpContext.Response;
                Stopwatch timer = (Stopwatch)httpContext.Items["Timer"];
                timer.Stop();
    
                // Don't interfere with non-HTML responses
                if (response.ContentType == "text/html")
                {
                    double seconds = (double)timer.ElapsedTicks / Stopwatch.Frequency;
                    string result_time = string.Format("{0:F4} sec ", seconds);
                    RenderQueriesToResponse(response,result_time);
                }
            };
        }
        void RenderQueriesToResponse(HttpResponse response, string result_time)
        {
            response.Write("<div style=\"margin: 5px; background-color: #FFFF00\"");
            response.Write(string.Format("<b>Page Generated in "+ result_time));
            response.Write("</div>");
        }
        public void Dispose() { /* Not needed */ }
    }
    

    您还可以添加一些样式到它。。。

    请记住在httpModules部分的WebConfig中注册您的模块:

      <add name="Name" type="namespace, dll"/>
    

    有关这方面的完整参考资料,请查看Steven Sanderson的Pro ASP.NET MVC框架-第15章-性能,监控页面生成时间。

    编辑:(comment@Pino) 以下是我的项目示例: alt text http://www.diarioplus.com/files/pictures/example_performance.JPG

        2
  •  16
  •   Kenny Eliasson    15 年前

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

    用它装饰每个控制器或动作方法,瞧,它在调试中吐出文本。

    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
    }
    

    现在,您已将executiontime保存在ViewData中,并可以在页面中访问它。。我通常这样把它放在母版上

    <!-- The page took <%= ViewData["ExecutionTime"] %> ms to execute -->
    
        3
  •  4
  •   Darin Dimitrov    15 年前

    这将取决于您希望在何处包含此信息。例如,您可以编写一个http处理程序,该处理程序将在 </html> 标签:

    public class RenderTimeModule : IHttpModule
    {
        public void Init(HttpApplication context)
        {
            context.BeginRequest += (sender, e) =>
            {
                var watch = new Stopwatch();
                var app = (HttpApplication)sender;
                app.Context.Items["Stopwatch"] = watch;
                watch.Start();
            };
    
            context.EndRequest += (sender, e) =>
            {
                var app = (HttpApplication)sender;
                var watch = (Stopwatch)app.Context.Items["Stopwatch"];
                watch.Stop();
                var ts = watch.Elapsed;
                string elapsedTime = String.Format("{0} ms", ts.TotalMilliseconds);
                app.Context.Response.Write(elapsedTime);
            };
        }
    
        public void Dispose()
        {
        }
    }
    

    如果要在HTML页面中间显示某个渲染时间,则此渲染时间将不考虑总页面渲染时间。