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

  • 相关阅读:
    导出表格,导出表格为excel,导出表格带样式,怎么导出表格数据为excel并且带样式呢
    webpack打包文件 可以npm cdn使用
    Webpack的externals的使用
    如何在微信小程序中使用iconfont
    如何发布和取消发布 NPM 包?
    js中数组对象去重的方法
    小程序列表性能优化
    wepy全局拦截器
    js中prototype与__proto__的关系详解
    JavaScript中本地对象、内置对象和宿主对象
  • 原文地址:https://www.cnblogs.com/chenxizhang/p/1438440.html
Copyright © 2011-2022 走看看