积极答复者
为什么我写的Module在一次页面访问执行多次?

问题
-
public class LoggingModule : IHttpModule
{
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.LogRequest += context_LogRequest;
}
void context_LogRequest(object sender, EventArgs e)
{
var application = (HttpApplication)sender;
var filepath = "e:\\log.txt";
using (var sw = new StreamWriter(filepath, true, Encoding.UTF8))
{
sw.AutoFlush = true;
sw.WriteLine("This is ");
foreach (var item in application.Modules)
{
sw.WriteLine(item.ToString());
}
}
}
}这是配置:
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true" >
<add name="LoggingModule" type="ModuleExtension.App_Code.LoggingModule" />
</modules>目的:页面被访问时写入log到一个txt,但我访问一次,Module里的代码执行了n次,这是为何?
答案
-
执行多次是因为你的网页中可能有多个请求,每一个请求发生就会执行一次LogRequest函数。要注意的是这请求的意义,不只是ASP.NET 页面请求,它还包括 CSS,JS,以及包括图片等...只要是该请求后缀被映射到ASP.NET处理程序的,都算是一个请求。
- 已标记为答案 Will ShaoMicrosoft employee, Moderator 2013年6月17日 9:25
全部回复
-
执行多次是因为你的网页中可能有多个请求,每一个请求发生就会执行一次LogRequest函数。要注意的是这请求的意义,不只是ASP.NET 页面请求,它还包括 CSS,JS,以及包括图片等...只要是该请求后缀被映射到ASP.NET处理程序的,都算是一个请求。
- 已标记为答案 Will ShaoMicrosoft employee, Moderator 2013年6月17日 9:25