2013-03-13 61 views
3

我想在我的ASP.NET应用程序的页脚中添加一个标签,显示我的用户每个页面加载的时间。在我site.master页我目前有:在ASP.NET主页的页脚中添加页面加载字符串

public partial class SiteMaster : MasterPage 
    { 
    public Stopwatch pageLoadTime = new Stopwatch(); 

    protected void Page_Load(object sender, EventArgs e) 
    { 
     pageLoadTime.Start(); 

     //Other stuff here 

     pageLoadTime.Stop(); 
     TimeSpan ts = pageLoadTime.Elapsed; 

     // Format and display the TimeSpan value. 
     string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds/10); 

     PageLoadTimeLabel.Text = "Page loaded in " + elapsedTime; 
    } 

但是,这是不是给我一个“真实”的网页加载时间,即使一个网页需要5秒钟加载它返回0.1秒。所以我将结尾代码移到Page_LoadComplete部分,但是这看起来不能更新标签。

任何指针?我知道我可以使用萤火虫等,但我希望我的用户能够轻松访问这些信息。

回答

3

我会做的global.asax

private DateTime start_time 

protected void Application_BeginRequest(object sender, EventArgs e) 
{ 
    start_time = DateTime.Now; 
} 
protected void Application_EndRequest(object sender, EventArgs e) 
{ 
    var duration = DateTime.Now - start_time; 
    Response.Write("..."); 
} 

或者写入到一个会话,并在你的母版页读取。

-1

Page.LoadComplete可以帮助你。如果您在Page_Load事件处理程序中启动计时器并在LoadComplete事件处理程序中停止它,那么您可能会得到实际时间。

1

感谢莱纳斯我创造了这个它做什么,我想:

protected void Application_BeginRequest(Object sender, EventArgs e) 
{ 
    Context.Items["loadstarttime"] = DateTime.Now; 
} 

然后

public void Application_EndRequest(object src, EventArgs e) 
{ 
    DateTime end = (DateTime)Context.Items["loadstarttime"]; 
    TimeSpan ts = DateTime.Now - end; 

    // Format and display the TimeSpan value. 
    string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds/10); 

    Response.Write("<div style='text-align: center' class='thesmallprint'>Page loaded in: " + elapsedTime + "</div>"); 
} 
+0

接受莱纳斯的答案,然后:-) – 2013-03-13 12:47:51