当前位置: 移动技术网 > IT编程>开发语言>.net > asp.net 通过httpModule计算页面的执行时间

asp.net 通过httpModule计算页面的执行时间

2017年12月12日  | 移动技术网IT编程  | 我要评论
创建一个类库,建立如下类: 复制代码 代码如下: using system; using system.collections.generic; using system.
创建一个类库,建立如下类:
复制代码 代码如下:

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)//实现ihttpmodules中的init事件
{
//订阅两个事件
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实例
//httpapplication实例里包含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>页面执行时间:" + (endtime - starttime).tostring() + "</p>");
}
//必须实现dispose接口
public void dispose() { }
}
}

生成后将dll文件copy到bin目录,接着在web.config中注册这个httpmodule:
复制代码 代码如下:

<configuration>
<system.web>
<httpmodules>
<add name="timerhttpmodule" type="timerhttpmodule.class1"/>
</httpmodules>
</system.web>
</configuration>

这样网站的每一个.net页面底部都会显示页面的执行时间了。
不过这样做要小心,因为每个.net页面末尾都会被加上执行时间,包括webservices和ashx页面,以及你可能不是用来直接做页面的.aspx页面(例如你用来输入json数据或者xml数据)。所以,为了保证安全,还必须采取有针对性的方法来避免这种情况的发生。
方法一:在response.write方法之前做判断,排除一些不想添加执行时间的页面,可以通过request.url来判断;
方法二:不要把执行时间直接添加到页面输出的尾端,而是作为一个http header输出。使用response.addheader(key,value)可以实现这个愿望。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网