zoukankan      html  css  js  c++  java
  • 在ASP.NET MVC中创建自定义模块

    创建模块

    module是实现了System.Web.IHttpModule接口的类。该接口定义了两个方法:

    Init:当模块初始化时被调用,传入的参数为HttpApplication对象,用于注册请求周期事件处理方法,并初始化所需要的资源。
    Dispose 当请求过程完成时调用,用于释放需显式管理的资源。
    在这个程序中,我们创建一个模块,拦截beginRequest和endRequest事件,实现了输出请求到响应的执行时间

    步骤:

      1. 创建TimerModule类,实现IHttpModule接口

      2. 在TimerModule,订阅需要拦截的事件

      3. 给事件添加事件处理程序

      4. 在Web.config中注册事件

    模块代码:

    public class TimerModule : IHttpModule
    {
        private Stopwatch timer;
        public void Dispose()
        {
        }
        public void Init(HttpApplication context)
        {
            context.BeginRequest += HandleEvent;
            context.EndRequest += HandleEvent;
        }
    
        private void HandleEvent(object sender, EventArgs e)
        {
            HttpContext ctx = HttpContext.Current;
            if (ctx.CurrentNotification==RequestNotification.BeginRequest)
            {
                timer = Stopwatch.StartNew();
            }
            else
            {
                ctx.Response.Write(string.Format(
                    "<div class='alert alert-success'>Elapsed:{0:F5} seconds</div>",
                    ((float)timer.ElapsedTicks)/Stopwatch.Frequency
                    ));
            }
        }
    }
    在Web.config中注册模块:
    <system.webServer>
        <modules>
          <add name="Timer" type="Test.Infrastructure.TimerModule"/>
        </modules>
    </system.webServer>
  • 相关阅读:
    硅谷独角兽公司的监控系统长啥样?
    通过jQuery设置全局Ajax加载时呈现Loading
    Jquery遮罩插件,想罩哪就罩哪!
    jquery 读取textarea内容
    easy ui layout 高度 宽度自适应浏览器
    css调节样式
    ORACLE数据库的连接
    spring cloud API网关
    嵌套查询与连接查询的性能
    对于where 1=1 这种条件传入需要'%s'
  • 原文地址:https://www.cnblogs.com/AlexanderZhao/p/10613090.html
Copyright © 2011-2022 走看看