Page generation time - ASP.Net MVC

前端 未结 3 463
遥遥无期
遥遥无期 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:27

    Yep the Derin Suggestion is the standard Way to do it in an ASP.NEt application, i would just suggest add an if so it does not interfere with non-HTML responses: EDIT: added complete implementation

    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("
    Page Generated in "+ result_time)); response.Write("
    "); } public void Dispose() { /* Not needed */ } }

    you can also add some style to it...

    And remember to register your Module in WebConfig inside httpModules Section:

      
    

    For a Complete Reference about this check the Pro ASP.NET MVC Framework by Steven Sanderson - Chapter 15 - Performance, Monitoring Page Generation Times.

    EDIT:(comment @Pino) Here is the example for my project: alt text http://www.diarioplus.com/files/pictures/example_performance.JPG

提交回复
热议问题