asp.net mvc为每个页面添加页面执行时间统计,这段代码自定义一个httpModule类,可以对所有页面进行执行时间统计,统计结果输出到header,你执行完页面查看header就可以看到有一个times的键值,就是执行时间,单位为毫秒
转载请注明出处:http://www.75271.com/codes/csharp/6235
定义httpModule的类
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MicroBlog.Web.Base { public class TimeHttpModule : IHttpModule { private DateTime starttime; public void Init(HttpApplication application)//实现IHttpModules中的Init事件 { //订阅两个事件 application.BeginRequest += new EventHandler(application_BeginRequest); application.EndRequest += new EventHandler(application_EndRequest); } 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; var ms = (endtime - starttime).Milliseconds; context.Response.Headers.Add("times", string.Format("{0}ms",ms.ToString())); } //必须实现dispose接口 public void Dispose() { } } }
在根目录下的web.config添加以下内容
<system.web> <httpModules> <add name="TimeHttpModule" type="MicroBlog.Web.Base.TimeHttpModule"/> </httpModules> </system.web> <system.webServer> <modules runAllManagedModulesForAllRequests="true"> <remove name="TimeHttpModule" /> <add name="TimeHttpModule" type="MicroBlog.Web.Base.TimeHttpModule" /> </modules> </system.webServer>
上面两处都需要添加