欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

asp.net 通過httpModule計(jì)算頁面的執(zhí)行時(shí)間

 更新時(shí)間:2011年02月19日 19:14:32   作者:  
有時(shí)候我們想檢測一下網(wǎng)頁的執(zhí)行效率。記錄下開始請求時(shí)的時(shí)間和頁面執(zhí)行完畢后的時(shí)間點(diǎn),這段時(shí)間差就是頁面的執(zhí)行時(shí)間了。要實(shí)現(xiàn)這個(gè)功能,通過HttpModule來實(shí)現(xiàn)是最方便而且準(zhǔn)確的。
創(chuàng)建一個(gè)類庫,建立如下類:
復(fù)制代碼 代碼如下:

using System;
using System.Collections.Generic;
using System.Web;//引用web命名空間
using System.Text;
namespace TimerHttpModule
{
public class Class1:IHttpModule//繼承IHttpModules
{
public void Init(HttpApplication application)//實(shí)現(xiàn)IHttpModules中的Init事件
{
//訂閱兩個(gè)事件
application.BeginRequest +=new EventHandler(application_BeginRequest);
application.EndRequest+=new EventHandler(application_EndRequest);
}
private DateTime starttime;
private void application_BeginRequest(object sender, EventArgs e)
{
//object sender是BeginRequest傳遞過來的對象
//里面存儲的就是HttpApplication實(shí)例
//HttpApplication實(shí)例里包含HttpContext屬性
starttime = DateTime.Now;
}
private void application_EndRequest(object sender, EventArgs e)
{
DateTime endtime = DateTime.Now;
HttpApplication application = (HttpApplication)sender;
HttpContext context = application.Context;
context.Response.Write("<p>頁面執(zhí)行時(shí)間:" + (endtime - starttime).ToString() + "</p>");
}
//必須實(shí)現(xiàn)dispose接口
public void Dispose() { }
}
}

生成后將dll文件copy到bin目錄,接著在web.config中注冊這個(gè)HttpModule:
復(fù)制代碼 代碼如下:

<configuration>
<system.web>
<httpModules>
<add name="TimerHttpModule" type="TimerHttpModule.Class1"/>
</httpModules>
</system.web>
</configuration>

這樣網(wǎng)站的每一個(gè).net頁面底部都會顯示頁面的執(zhí)行時(shí)間了。
不過這樣做要小心,因?yàn)槊總€(gè).net頁面末尾都會被加上執(zhí)行時(shí)間,包括webservices和ashx頁面,以及你可能不是用來直接做頁面的.aspx頁面(例如你用來輸入json數(shù)據(jù)或者xml數(shù)據(jù))。所以,為了保證安全,還必須采取有針對性的方法來避免這種情況的發(fā)生。
方法一:在Response.Write方法之前做判斷,排除一些不想添加執(zhí)行時(shí)間的頁面,可以通過Request.URL來判斷;
方法二:不要把執(zhí)行時(shí)間直接添加到頁面輸出的尾端,而是作為一個(gè)http header輸出。使用Response.AddHeader(key,value)可以實(shí)現(xiàn)這個(gè)愿望。

相關(guān)文章

最新評論