zoukankan      html  css  js  c++  java
  • 如何在ASP.NET站点中实现对用户请求的监控

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

    要做这样的事情,其实重点是要理解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引擎来处理的。那么怎么样改变这个行为呢?我们可以修改站点的配置

    image

    点击“配置”

    image

    点击“添加”

    image

  • 相关阅读:
    【剑指offer】二叉搜索树与双向链表
    【剑指offer】复杂链表的复制
    【剑指offer】二叉树中和为某一值的路径
    2018.12.30 Intellij IDEA设置main方法自动补全
    2018.12.29 Spring FrameWork各个版本下载
    2018.12.26 Mac下的Eclipse在编辑Spring配置文件xml时自动提示类class包名配置
    2018.12.25 Spring中JDBCTemplate模版API学习
    2018.12.24 Spring中的aop演示(也就是运用aop技术实现代理模式)
    2018.12.22 Spring学习02
    2018.12.24 Ubuntu18.0.4 主题参考
  • 原文地址:https://www.cnblogs.com/chenxizhang/p/1438440.html
Copyright © 2011-2022 走看看