asp.net calculates the execution time of the page through httpModule

  • 2020-05-12 02:28:53
  • OfStack

Create a class library and create the following class:
 
using System; 
using System.Collections.Generic; 
using System.Web;// reference web The namespace  
using System.Text; 
namespace TimerHttpModule 
{ 
public class Class1:IHttpModule// inheritance IHttpModules 
{ 
public void Init(HttpApplication application)// implementation IHttpModules In the Init The event  
{ 
// Subscribe to two events  
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 is BeginRequest The object passed in  
// That's what it stores HttpApplication The instance  
//HttpApplication The instance contains HttpContext attribute  
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> Page execution time: " + (endtime - starttime).ToString() + "</p>"); 
} 
// Must be implemented dispose interface  
public void Dispose() { } 
} 
} 

Once generated, the dll file copy is added to the bin directory, and then the HttpModule is registered in web.config:
 
<configuration> 
<system.web> 
<httpModules> 
<add name="TimerHttpModule" type="TimerHttpModule.Class1"/> 
</httpModules> 
</system.web> 
</configuration> 

This will display the page execution time at the bottom of every.net page on the site.
Be careful, though, because the execution time is added to the end of every.net page, including webservices and ashx pages, and aspx pages that you may not be using to make the page directly (for example, if you are using to enter json data or xml data). Therefore, in order to ensure security, targeted measures must be taken to avoid this situation.
Method 1: make a judgment before Response.Write method, exclude 1 page that do not want to add execution time, you can judge by Request.URL;
Method 2: do not add the execution time directly to the end of the page output, but as an http header output. You can do this with Response.AddHeader (key,value).

Related articles: