Create a class library and create the following classes:
Copy codeThe Code is as follows: using System;
Using System. Collections. Generic;
Using System. Web; // reference the web namespace
Using System. Text;
Namespace TimerHttpModule
{
Public class Class1: IHttpModule // inherits IHttpModules
{
Public void Init (HttpApplication application) // implement the Init event in IHttpModules
{
// 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 the object passed by BeginRequest.
// It stores the HttpApplication instance.
// The HttpApplication instance contains the 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> ");
}
// The dispose interface must be implemented
Public void Dispose (){}
}
}
After the dll file is generated, copy it to the bin directory and register the HttpModule in web. config:Copy codeThe Code is as follows: <configuration>
<System. web>
<HttpModules>
<Add name = "TimerHttpModule" type = "TimerHttpModule. Class1"/>
</HttpModules>
</System. web>
</Configuration>
In this way, the execution time of the page is displayed at the bottom of each. net page of the website.
But be careful when doing this, because every. the execution time will be added at the end of the net page, including webservices and ashx pages, and you may not be used to directly create pages. aspx page (for example, json data or xml data ). Therefore, to ensure security, we must also adopt targeted methods to avoid this situation.
Method 1: make a judgment before the Response. Write method. to exclude some pages that do not want to add execution time, you can use Request. URL to judge;
Method 2: Do not add the execution time directly to the end of the page output, but act as an http header output. Response. AddHeader (key, value) can be used to achieve this desire.