Page Render Time in MVC

后端 未结 4 558
误落风尘
误落风尘 2021-02-06 05:45

Q: How do I calculate the total time it takes to render an MVC page and display the time on the master page.

In Asp.net Web Form I created a Base page class like so:

4条回答
  •  青春惊慌失措
    2021-02-06 06:41

    Create a base controller and have your controllers derive from it. Set your start time in the constructor and override Dispose() and put the calculation of the total time there. This should give you an end-to-end on the entire life of the action. Since Controller implements IDisposable, I'm assuming that the render engine will dispose it after the result is computed and you won't have to wait for garbage collection. If my assumption turns out to be wrong, you could use OnResultExecuted() instead.

    EDIT: To get the rendering time on the page would be relatively hard because by definition the page can't be done rendering until your time is put on the page and you can't have the time until the page is done rendering. You could, however, write the render time to the session then use AJAX to come back and get the render time for display later. You might be able to approximate it by putting the start time in ViewData and calculating the rendering time in the View itself. You might want to try logging the render time and doing the view approximation and see how close it is.

    This code could be used to log the render time.

    public class BaseController : Controller
    {
       private DateTime StartTime { get; set; }
       public BaseController() : base()
       {
           StartTime = DateTime.Now;
       }
    
       public override void Dispose( bool disposing )
       {
           var totalTime = DateTime.Now - this.StartTime;
           ... write it out somewhere ...
       }
    }
    

提交回复
热议问题