在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>

 

转载于:https://www.cnblogs.com/AlexanderZhao/p/10613090.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值