您的位置:首页 > 编程语言 > ASP

如何在ASP.NET站点中实现对用户请求的监控

2009-04-17 23:21 435 查看
今天在讲课的间隙,有朋友问到这个问题:一个站点中,如果希望监控到用户请求的地址,不管是他通过在地址栏输入地址,还是通过点击链接来请求的。

要做这样的事情,其实重点是要理解APS.NET的HttpModule的机制。我们可以编写一个自定义的HttpModule,专门地监控这个行为。

为此,请按照下面的步骤来做

1. 定义一个新的HttpModule

public class RequestMonitorModule:IHttpModule
{
#region IHttpModule 成员 public void Dispose()
{
} public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(context_BeginRequest);
} void context_BeginRequest(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
string url = app.Request.Url.AbsolutePath; string path = app.Server.MapPath("Log.txt"); FileStream fs = new FileStream(path, FileMode.Append);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(string.Format("地址:{0},时间{1}", url, DateTime.Now.ToString())); sw.Close();
/// } #endregion
} 这里的关键就在于实现IHttpModule接口,并在Init方法中为application的BeginRequest事件绑定一个事件处理程序。

2.注册该Module

<httpModules>
<add name="MyModule" type="MyWebApplication.RequestMonitorModule"/>
</httpModules> 3. 然后就可以进行测试了

输出的日志文件大致如下

地址:/test/default.aspx,时间2009-4-17 17:56:39
地址:/test/Product.aspx,时间2009-4-17 17:56:44
地址:/test/Product.aspx,时间2009-4-17 17:57:22
地址:/test/default.aspx,时间2009-4-17 18:00:42
地址:/test/Test.htm,时间2009-4-17 18:00:47

【注意】如果在VS里面调试的话,htm页面也能被监控到的,但如果真的部署到了IIS,就没有了。是因为在IIS上面,htm页面是不会交给ASP.NET引擎来处理的。那么怎么样改变这个行为呢?我们可以修改站点的配置





点击“配置”





点击“添加”



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐