Page generation time - ASP.Net MVC

前端 未结 3 469
遥遥无期
遥遥无期 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-12 18:03

    It will depend on where you want to include this information. For example you could write an http handler that will display the render time after the tag:

    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()
        {
        }
    }
    

    If you want to display render time somewhere in the middle of the html page then this render time will not account for the total page render time.

提交回复
热议问题